Typescript objects serialization?

前端 未结 5 1468
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  Happy的楠姐
    2021-02-02 07:16

    Use Interfaces to get strong types:

    // Creating 
    var foo:any = {};
    foo.x = 3;
    foo.y='123';
    
    var jsonString = JSON.stringify(foo);
    alert(jsonString);
    
    
    // Reading
    interface Bar{
        x:number;
        y?:string; 
    }
    
    var baz:Bar = JSON.parse(jsonString);
    alert(baz.y);
    

    And use type assertion "<>" if you need to.

提交回复
热议问题