Created
November 6, 2021 08:28
-
-
Save LuisMiguelFilipe/56b26513d31a0b452f4d1356737ffd5c to your computer and use it in GitHub Desktop.
Javascript calculated property which is serializable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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