Skip to content

Expose getters to JSON.stringify by generating a toJSON method #16858

@HarmenM

Description

@HarmenM

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Out of ScopeThis idea sits outside of the TypeScript language design constraints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions