Typescript objects serialization?

前端 未结 5 1394
隐瞒了意图╮
隐瞒了意图╮ 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:11

    First, you need to create an interface of your source entity which you receive from the API as JSON:

    interface UserEntity {
      name: string,
      age: number,
      country_code: string 
    };
    

    Second implement your model with constructor where you can customize (camelize) some field names:

      class User  { 
        constructor({ name, age, country_code: countryCode }: UserEntity) {
          Object.assign(this, { name, age, countryCode });
        }
      }
    

    Last create instance of your User model using JS object jsonUser"

        const jsonUser = {name: 'Ted', age: 2, country_code: 'US'};
    
        const userInstance = new User(jsonUser);
        
        console.log({ userInstance })
    

    Here is the link to playground

提交回复
热议问题