How do I initialize a TypeScript object with a JSON object

前端 未结 16 720
被撕碎了的回忆
被撕碎了的回忆 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 09:05

    Option #5: Using Typescript constructors and jQuery.extend

    This seems to be the most maintainable method: add a constructor that takes as parameter the json structure, and extend the json object. That way you can parse a json structure into the whole application model.

    There is no need to create interfaces, or listing properties in constructor.

    export class Company
    {
        Employees : Employee[];
    
        constructor( jsonData: any )
        {
            jQuery.extend( this, jsonData);
    
            // apply the same principle to linked objects:
            if ( jsonData.Employees )
                this.Employees = jQuery.map( jsonData.Employees , (emp) => {
                    return new Employee ( emp );  });
        }
    
        calculateSalaries() : void { .... }
    }
    
    export class Employee
    {
        name: string;
        salary: number;
        city: string;
    
        constructor( jsonData: any )
        {
            jQuery.extend( this, jsonData);
    
            // case where your object's property does not match the json's:
            this.city = jsonData.town;
        }
    }
    

    In your ajax callback where you receive a company to calculate salaries:

    onReceiveCompany( jsonCompany : any ) 
    {
       let newCompany = new Company( jsonCompany );
    
       // call the methods on your newCompany object ...
       newCompany.calculateSalaries()
    }
    

提交回复
热议问题