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
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