Skip to content

Instantly share code, notes, and snippets.

@theredhead
Created June 22, 2020 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theredhead/e49ffa7bf85d623d39499a98ada4bc66 to your computer and use it in GitHub Desktop.
Save theredhead/e49ffa7bf85d623d39499a98ada4bc66 to your computer and use it in GitHub Desktop.
Annotate a field in a typescript class to store its' content in localstorage transparently.
//
// Inspired by https://github.com/zhaosiyang/property-watch-decorator/blob/master/src/index.ts
//
// Annotate a field in a typescript class to store its' content in localstorage transparently.
//
export function Preference<T = any>(preferenceKey: string, defaultValueObj: T) {
return (target: any, key: PropertyKey) => {
Object.defineProperty(target, key, {
set: function(value) {
localStorage.setItem(preferenceKey, JSON.stringify(value));
},
get: function() {
const rawValue = window.localStorage.getItem(preferenceKey);
const value = rawValue !== null && rawValue !== undefined ? <T>JSON.parse(rawValue) : defaultValueObj;
return value;
},
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment