LocalStorage.ts
A typed localStorage wrapper with namespaced keys and typed getters and setters.
1 min read
Updated
A typed localStorage wrapper: it namespaces keys with a prefix and returns a typed object with getters and setters, so reads and writes stay consistent across a codebase. The TypeScript source is below.
LocalStorage.ts
typescript
type Methods = {
clear(): void;
};
export function createLocalStorage<T extends Record<string, string>>(prefix: string, properties: T): Partial<T> & Methods {
function key(prop: string) {
return `${prefix}:${prop}`;
}
function clear() {
for (const key in properties) {
delete proxy[key];
}
}
const proxy = new Proxy(properties, {
get(target, property: string, receiver) {
if (property === 'clear') {
return clear;
}
return target[property] ?? localStorage.getItem(key(property));
},
set(target: Record<string, string>, property: string, value, receiver) {
localStorage.setItem(key(property), value);
target[property] = value;
return true;
},
deleteProperty(target: Record<string, string>, property: string) {
localStorage.removeItem(key(property));
target[property] = '';
return true;
},
});
// preload properties
const obj = properties as Record<string, string>;
for (const property in properties) {
const value = localStorage.getItem(key(property)) || properties[property];
if (value) {
(proxy as Record<string, string>)[property] = value;
} else {
obj[property] = value;
}
}
return proxy as any;
}