Using JSON.stringify in conjunction with TypeScript getter/setter

前端 未结 4 988
小蘑菇
小蘑菇 2020-12-11 01:12

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,

4条回答
  •  天命终不由人
    2020-12-11 02:09

    No, you can't have JSON.stringify using the getter/setter name instead of the property name.

    But you can do something like this:

    class Version {
        private _major: number;
    
        get major(): number {
            return this._major;
        }
    
        set major(major: number) {
            this._major = major;
        }
    
        toJsonString(): string {
            let json = JSON.stringify(this);
            Object.keys(this).filter(key => key[0] === "_").forEach(key => {
                json = json.replace(key, key.substring(1));
            });
    
            return json;
        }
    }
    
    let version = new Version();
    version.major = 2;
    console.log(version.toJsonString()); // {"major":2}
    

提交回复
热议问题