Skip to content

Instantly share code, notes, and snippets.

@srvice-temp
Last active December 12, 2023 09:46
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srvice-temp/046126458bbed2239e0b8d6403bced18 to your computer and use it in GitHub Desktop.
Save srvice-temp/046126458bbed2239e0b8d6403bced18 to your computer and use it in GitHub Desktop.
localStorage utility for typescript - keep track of types! πŸ˜€
// store objects and keep track of types with Window.localStorage
// (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)
interface Bar {}
export enum CacheKey {
Foo = 'Foo'
}
interface CacheValues {
[CacheKey.Foo]: Bar;
}
interface CacheUtil {
set: <T extends CacheKey>(key: T, object: CacheValues[T]) => void;
get: <T extends CacheKey>(key: T) => CacheValues[T];
remove: (key: CacheKey) => void;
removeAll: () => void;
}
export const cacheUtil: CacheUtil = {
set: (key, object) => {
localStorage.setItem(key, JSON.stringify(object));
},
get: key => JSON.parse(localStorage.getItem(key) ?? {}),
remove: (key) => localStorage.removeItem(key),
removeAll: () => localStorage.clear(),
};
// check out the following StackOverflow link for a collection of other useful localStorage functions
// https://stackoverflow.com/questions/34245593/html5-localstorage-useful-functions-javascript-typescript
@Kyubinhan
Copy link

why would you use ?? in line 25? JSON.parse('') will throw an exception

@Vanuan
Copy link

Vanuan commented Mar 28, 2023

JSON.parse expects a string. {} is not a string. You need to use quotes

@Fernandos77
Copy link

JSON.parse(localStorage.getItem(key) ?? "{}")
thank you for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment