typescript parse json with class and interface

后端 未结 1 1932
小蘑菇
小蘑菇 2021-02-07 21:08

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

相关标签:
1条回答
  • 2021-02-07 21:51

    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.
    
    0 讨论(0)
提交回复
热议问题