How do I initialize a TypeScript object with a JSON object

前端 未结 16 721
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 08:30

I receive a JSON object from an AJAX call to a REST server. This object has property names that match my TypeScript class (this is a follow-on to this question).

Wha

16条回答
  •  灰色年华
    2020-11-22 08:54

    For simple objects, I like this method:

    class Person {
      constructor(
        public id: String, 
        public name: String, 
        public title: String) {};
    
      static deserialize(input:any): Person {
        return new Person(input.id, input.name, input.title);
      }
    }
    
    var person = Person.deserialize({id: 'P123', name: 'Bob', title: 'Mr'});
    

    Leveraging the ability to define properties in the constructor lets it be concise.

    This gets you a typed object (vs all the answers that use Object.assign or some variant, which give you an Object) and doesn't require external libraries or decorators.

提交回复
热议问题