Typescript objects serialization?

前端 未结 5 1393
隐瞒了意图╮
隐瞒了意图╮ 2021-02-02 06:40

Are there any means for JSON serialization/deserialization of Typescript objects so that they don\'t loose type information? Simple JSON.parse(JSON.stringify) has t

5条回答
  •  无人共我
    2021-02-02 07:08

    I think a better way to handle this is to use Object.assign (which however requires ECMAScript 2015).

    Given a class

    class Pet {
        name: string;
        age: number;
        constructor(name?: string, age?: number) {
            this.name = name;
            this.age = age;
        }
        getDescription(): string {
            return "My pet " + this.name + " is " + this.age + " years old.";
        }
        static fromJSON(d: Object): Pet {
            return Object.assign(new Pet(), d);
        }
    }
    

    Serialize and deserialize like this...

    var p0 = new Pet("Fido", 5);
    var s = JSON.stringify(p0);
    var p1 = Pet.fromJSON(JSON.parse(s));
    console.log(p1.getDescription());
    

    To take this example to the next level, consider nested objects...

    class Type {
        kind: string;
        breed: string;
        constructor(kind?: string, breed?: string) {
            this.kind = kind;
            this.breed = breed;
        }
        static fromJSON(d: Object) {
            return Object.assign(new Type(), d);
        }
    }
    class Pet {
        name: string;
        age: number;
        type: Type;
        constructor(name?: string, age?: number) {
            this.name = name;
            this.age = age;
        }
        getDescription(): string {
            return "My pet " + this.name + " is " + this.age + " years old.";
        }
        getFullDescription(): string {
            return "My " + this.type.kind + ", a " + this.type.breed + ", is " + this.age + " years old.";
        }
        static fromJSON(d: Object): Pet {
            var o = Object.assign(new Pet(), d);
            o.type = Type.fromJSON(o['type']);
            return o;
        }
    }
    

    Serialize and deserialize like this...

    var q0 = new Pet("Fido", 5);
    q0.type = new Type("dog", "Pomeranian");
    var t = JSON.stringify(q0);
    var q1 = Pet.fromJSON(JSON.parse(t));
    console.log(q1.getFullDescription());
    

    So unlike using an interface, this approach preserves methods.

提交回复
热议问题