Using JSON.stringify in conjunction with TypeScript getter/setter

前端 未结 4 984
小蘑菇
小蘑菇 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 01:48

    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

    0 讨论(0)
  • 2020-12-11 01:52

    I've written a small library ts-typed, which generate getter/setter for runtime typing purpose. I've faced the same problem when using JSON.stringify(). So i've solved it by adding a kind of serializer, and proposing to implement a kind of toString (in Java) buy calling it toJSON.

    Here is an example:

    import { TypedSerializer } from 'ts-typed';
    
    export class RuntimeTypedClass {
        private _major: number;
    
        get major(): number {
           return this._major;
        }
    
        set major(major: number) {
           this._major = major;
        }
        /**
        * toString equivalent, allows you to remove the _ prefix from props.
        *
        */
        toJSON(): RuntimeTypedClass {
            return TypedSerializer.serialize(this);
        }
    }
    
    0 讨论(0)
  • 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}
    
    0 讨论(0)
  • 2020-12-11 02:11

    I think iterating through the properties and string manipulating is dangerous. I would do using the prototype of the object itself, something like this:

    public static toJSONString() : string {
        return JSON.stringify(this, Object.keys(this.constructor.prototype)); // this is version class
    }
    
    0 讨论(0)
提交回复
热议问题