Created
May 17, 2023 22:02
-
-
Save mikoloism/71b1be8846f69572069cc1e99d9ad675 to your computer and use it in GitHub Desktop.
Class based `localStorage` API
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
export class storage { | |
public static canUse(): boolean { | |
return typeof localStorage !== 'undefined'; | |
} | |
public static hasKey(key: string): boolean { | |
return storage.canUse() && localStorage.getItem(key) !== null; | |
} | |
public static getJson<T>(key: string): T | null { | |
if (storage.canUse()) { | |
const raw = localStorage.getItem(key); | |
if (raw !== null) { | |
return JSON.parse(raw); | |
} | |
} | |
return null; | |
} | |
public static setJson<T>(key: string, json: T): void { | |
if (storage.canUse()) { | |
const raw = JSON.stringify(json); | |
localStorage.setItem(key, raw); | |
} | |
} | |
public static removeKey(key: string): void { | |
if (storage.canUse()) { | |
localStorage.removeItem(key); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment