1

In Angular2 (TypeScript) I have a class with the following constructor:

 export class DataModel {
    constructor(public date_of_visit: string,
                public gender: boolean,
                public year_of_birth: number,
                public height: number,
                public weight: number){}
 }

I have the following JSON object:

json = {"date_of_visit": "23/09/2016", "gender": 1, "year_of_birth": 1975, "height":185, "weight": 85}

Question: Whats the easiest way to create a DataModel instance with the JSON data as input? Something like new DataModel(**json)

1

2 Answers 2

1

For compile time casting, this will do:

let dataModel = {"date_of_visit": "23/09/2016", "gender": 1, "year_of_birth": 1975, "height":185, "weight": 85} as DataModel;
Sign up to request clarification or add additional context in comments.

5 Comments

FYI, this is a type-assertion, which is a compile-time construct, and not a type-cast, which would be a runtime-time construct. This effectively means that the object created from parsing the JSON will be an Object instance at runtime, and not a DataModel instance. This is fine as long as you don't use instanceof, or define methods, getters, setters, or anything that is not inherently present in the parsed JSON itself.
Thanks for clarifying that @JohnWhite. I think the answer Im looking for is type-cast, because I need to call methods of DataModel. Can you show an example of this?
I think I found the answer here: stackoverflow.com/questions/32167593/…
IMO, this is a complete unknown in TypeScript for now. There is no standardized methodology for doing an actual type-cast, which can be credited to the relatively young age of TypeScript, and that one of its goals is minimizing any runtime overhead. However, there's an experimental project I started working on, TypedJSON, which does exactly what you are looking for: creating a user-defined class instance from JSON. It has its limitations, but it is solid for general use, and its syntax is extremely lightweight. I can post an answer with it.
I'll take a look at your project, thanks for your guidance.
0

Casting should get you through:

let model: DataModel = {"date_of_visit": "23/09/2016", "gender": 1, "year_of_birth": 1975, "height":185, "weight": 85} as DataModel;

1 Comment

It is worth noting that the preferred way of doing a type-assertion is obj as Type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.