对象打字稿/离子3的接口

时间:2018-06-14 22:27:41

标签: javascript typescript ionic-framework ionic3

我有一个从api返回的json对象,并且想要创建一个包含该对象包含的字段的接口。我正在使用离子3框架。我想要如何创建这个接口的帮助。(我很困惑:我应该为数据创建另一个接口?如果是的话如何将它包含在主界面中?)对象结构如下:

{

"status": "success",

"data": [

      {

          "id": 113,

          "subject": "hello there",

          "body": "i am hisham",

          "sender": {

              "id": 51,

              "country": {

                  "id": 9,

                  "name_en": "Syria",

              }

          }

      },

      {

          "id": 114,

          "subject": "hello there",

          "body": "i am lkfdj",

          "sender": {

              "id": 54,

              "country": {

                  "id": 9,

                  "name_en": "Syria",
              }

          }

      }

  ]

}

1 个答案:

答案 0 :(得分:3)

如果要定义接口,则应为响应中的每个对象定义一个接口。你没有必要,但为了获得正确的类型完成,你应该。

interface Response {
  status: string;
  data: Data[];
}

interface Data {
  id: number;
  subject: string;
  body: string;
  sender: Sender;
}

interface Sender {
  id: number;
  country: Country;
}

interface Country {
  id: number;
  name_en: string;
}