Skip to content

Instantly share code, notes, and snippets.

@mikoloism
Created May 17, 2023 22:02
Show Gist options
  • Save mikoloism/71b1be8846f69572069cc1e99d9ad675 to your computer and use it in GitHub Desktop.
Save mikoloism/71b1be8846f69572069cc1e99d9ad675 to your computer and use it in GitHub Desktop.
Class based `localStorage` API
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