TypeScript Version: All
Problem
Currently getters are not called when an initialized Typescript object is serialized into JSON. While it is logical runtime behaviour of javascript, it feels not like the desired behaviour from a 'Typescript point of view', the transpiled Class behaves not as the getter implies, to be a public property of the class.
export class TestClass
{
private _value:string = "value";
get value():string
{
return this._value;
}
}
let obj = new TestClass();
console.log(JSON.stringify(obj)); //{"_value":"value"}
The outputted JSON contains the private value property: {"_value":"value"}, instead of an evaluated getter. {"value":"value"}
In order to fix this a toJSON method could be implemented:
export class TestClass
{
private _value:string = "value";
get value():string
{
return this._value;
}
public toJSON()
{
return {
value: this.value
};
}
}
let obj = new TestClass();
console.log(JSON.stringify(obj)); //{"value":"value"}
Suggestion
It is my suggestion that Typescript would automatically add a toJSON method on transpilation, if the following conditions apply:
- There are getters present in a class
- There is not already a
toJSON method implemented in the class or its parent classes.
The generated toJSON method could expose (optionally only) all public properties and getters.
TypeScript Version: All
Problem
Currently getters are not called when an initialized Typescript object is serialized into JSON. While it is logical runtime behaviour of javascript, it feels not like the desired behaviour from a 'Typescript point of view', the transpiled Class behaves not as the getter implies, to be a public property of the class.
The outputted JSON contains the private value property:
{"_value":"value"}, instead of an evaluated getter.{"value":"value"}In order to fix this a
toJSONmethod could be implemented:Suggestion
It is my suggestion that Typescript would automatically add a
toJSONmethod on transpilation, if the following conditions apply:toJSONmethod implemented in the class or its parent classes.The generated
toJSONmethod could expose (optionally only) all public properties and getters.