How do I initialize a TypeScript object with a JSON object

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

    I've created a tool that generates TypeScript interfaces and a runtime "type map" for performing runtime typechecking against the results of JSON.parse: ts.quicktype.io

    For example, given this JSON:

    {
      "name": "David",
      "pets": [
        {
          "name": "Smoochie",
          "species": "rhino"
        }
      ]
    }
    

    quicktype produces the following TypeScript interface and type map:

    export interface Person {
        name: string;
        pets: Pet[];
    }
    
    export interface Pet {
        name:    string;
        species: string;
    }
    
    const typeMap: any = {
        Person: {
            name: "string",
            pets: array(object("Pet")),
        },
        Pet: {
            name: "string",
            species: "string",
        },
    };
    

    Then we check the result of JSON.parse against the type map:

    export function fromJson(json: string): Person {
        return cast(JSON.parse(json), object("Person"));
    }
    

    I've left out some code, but you can try quicktype for the details.

提交回复
热议问题