Skip to content

Instantly share code, notes, and snippets.

@LuisMiguelFilipe
Created November 6, 2021 08:28
Show Gist options
  • Save LuisMiguelFilipe/56b26513d31a0b452f4d1356737ffd5c to your computer and use it in GitHub Desktop.
Save LuisMiguelFilipe/56b26513d31a0b452f4d1356737ffd5c to your computer and use it in GitHub Desktop.
Javascript calculated property which is serializable
// Typescript accessor fields are not part of the serilization process
// A Proxy object serves the purpose ina very elegant way
// Other alternative would be to use `Object.defineProperty`
class Q {
constructor(init: number) {
var proxy = new Proxy(this, {
get: (target, prop, receiver) => {
if (prop === "msg") {
return `Number is ${this.value}`;
}
return Reflect.get(target, prop, receiver);
},
});
this.value = init;
return proxy;
}
value: number;
readonly msg: string|undefined = undefined; // must have an explicit value; if not, the property will not exist in the object
}
var q = new Q(42);
var s = JSON.stringify(q);
console.log(s); // msg is part of the serialized object
console.log(q);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment