Skip to content

Instantly share code, notes, and snippets.

@Snoupix
Last active July 20, 2023 13:07
Show Gist options
  • Select an option

  • Save Snoupix/a28eac85ec9241cf85320ec1cafb85e1 to your computer and use it in GitHub Desktop.

Select an option

Save Snoupix/a28eac85ec9241cf85320ec1cafb85e1 to your computer and use it in GitHub Desktop.
const appName = "AppName";
export type LocalStorage = {
theme: "dark" | "light"
items: Array<Item>
}
export type Item = {
id: string
}
type StorageType<T> = T extends keyof LocalStorage ? LocalStorage[T] : never;
export const SetStorageValue = (value: Partial<LocalStorage>): void => {
if (!localStorage) throw new Error("Cannot access localStorage");
const storage = localStorage.getItem(appName);
if (storage == null) {
localStorage.setItem(appName, JSON.stringify(value));
return;
}
const parsedStorage = JSON.parse(storage);
localStorage.setItem(appName, JSON.stringify({ ...parsedStorage, ...value }));
return;
}
export function GetStorageValue<T extends keyof LocalStorage>(value: T): StorageType<T> | null {
if (!localStorage) return null;
const storageObject = JSON.parse(localStorage.getItem(appName) || "{}") as LocalStorage;
return storageObject[value] as StorageType<T>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment