Skip to content

Instantly share code, notes, and snippets.

@difosfor
Created July 6, 2020 15:03
Show Gist options
  • Save difosfor/373da4b9ea92149fe85591b0cf4d91b4 to your computer and use it in GitHub Desktop.
Save difosfor/373da4b9ea92149fe85591b0cf4d91b4 to your computer and use it in GitHub Desktop.
Typed localStorage
export class TypedStorage<Items> {
private prefix: string;
constructor(prefix: string) {
this.prefix = prefix;
}
public delete<Key extends keyof Items>(key: Key) {
const value = this.get(key);
const prefixedKey = this.getPrefixedKey(key);
localStorage.removeItem(prefixedKey);
return value;
}
public get<Key extends keyof Items>(key: Key, defaultValue?: Items[Key]) {
const prefixedKey = this.getPrefixedKey(key);
const value = localStorage.getItem(prefixedKey);
return value === null ? defaultValue : JSON.parse(value);
}
public set<Key extends keyof Items>(key: Key, value: Items[Key]) {
const prefixedKey = this.getPrefixedKey(key);
try {
localStorage.setItem(prefixedKey, JSON.stringify(value));
} catch (error) {
console.log(`Failed to persist ${prefixedKey} in localStorage`, error);
}
}
private getPrefixedKey<Key extends keyof Items>(key: Key) {
return `${this.prefix}${key}`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment