Using JSON.stringify in conjunction with TypeScript getter/setter

Dominic picture Dominic · Oct 17, 2016 · Viewed 8.2k times · Source

I am using getter/setter accessors in TypeScript. As it is not possible to have the same name for a variable and method, I started to prefix the variable with a lower dash, as is done in many examples:

private _major: number;

get major(): number {
  return this._major;
}
set major(major: number) {
  this._major = major;
}

Now when I use the JSON.stringify() method to convert the object into a JSON string, it will use the variable name as the key: _major.

As I don't want the JSON file to have all keys prefixed with a lower dash, is there any possibility to make TypeScript use the name of the getter method, if available? Or are there any other ways to use the getter/setter methods but still produce a clean JSON output?

I know that there are ways to manually modify the JSON keys before they are written to the string output. I am curious if there is simpler solution though.

Here is a JSFiddle which demonstrates the current behaviour.

Answer

alacambra picture alacambra · May 29, 2017

based on @Jan-Aagaard solution I have tested this one

public toJSON(): string {
    let obj = Object.assign(this);
    let keys = Object.keys(this.constructor.prototype);
    obj.toJSON = undefined;
    return JSON.stringify(obj, keys);
}

in order to use the toJSON method