I\'m trying to make a class Post contains post attributes such as \"id, title, content ...etc.
I want to initialize the class from a JSON response. I\'m
You should definitely use interfaces to describe your DTO (Data Transfer Object). It looks like the json2ts did a good job in describing your JSON structure. Now, because the http service created the object for you, you don't have to create a new one... you only have to cast it to your interface, something like in the following lines:
class AppComponent {
dataFromServer : RootObject;
http.get('http://localhost/wptest/wp-json/wp/v2/posts').subscribe(res => {
this.dataFromServer = <RootObject>res.json();
});
}
From that point TypeScript will guard you from doing any mistakes when you try to access any data that came from the server. For example:
this.dataFromServer.age = 45; // Error: age doesn't exist in the RootObject interface
this.id = "Hello"; // Error, id was is a number, and you try to put string into it.
this.id = 100; // will be just fine.