Last active
July 20, 2023 13:07
-
-
Save Snoupix/a28eac85ec9241cf85320ec1cafb85e1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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