簡體   English   中英

Typescript:如何為嵌套對象數組定義接口

[英]Typescript: How do I define interfaces for nested objects array

假設我有一個 JSON 有效載荷解析成這樣的東西

{
  "status": "123",
  "totalResults": 1234,
  "articles": [
    {
      "source": {
        "id": "123",
        "name": "123"
      },
      "author": "123",
      "title": "123",
      "url": "123",
      "imgUrl": "123",
      "publishedAt": "123",
      "content": "123"
    },
]
}

我如何將 Example 接口的定義設置為 model,即 items 屬性的值為 object,其鍵為字符串,其值由 Item 接口定義:

interface Item {
    status: string;
    totalResults: number;
    id: string
    name: string
    author: string
    title: string
    description: string
    url: string
    urlToImage: string
    publishedAt: string
    content: string
}

interface Example extends Item{
    articles: Array<Object>;
    source: {
     [key: string]: Item
    };
}


const example: Example = {
  "status": "123",
  "totalResults": 1,
  "articles": [
    {
      "source": {
        "id": "123",
        "name": "123"
      },
      "author": "123",
      "title": '123',
      "description": "123",
      "url": "123",
      "urlToImage": "123",
      "publishedAt": "123",
      "content": "123"
    },
  ]
}

這是一個正確鍵入的版本,但我不確定這是否是您正在尋找的。

interface Item {
    status: string;
    totalResults: number;
    articles: Array<Articles>;
}

interface Articles {
    source: Source // or source: { id: string; name: string };
    author: string;
    title: string;
    description: string;
    url: string;
    urlToImage: string;
    publishedAt: string;
    content: string;
}

interface Source {
    id: string;
    name: string;
}

const example: Item = {
    "status": "123",
    "totalResults": 1,
    "articles": [
    {
        "source": {
            "id": "123",
            "name": "123"
        },
        "author": "123",
        "title": '123',
        "description": "123",
        "url": "123",
        "urlToImage": "123",
        "publishedAt": "123",
        "content": "123"
    },
    ]
}
export interface Reference{
  status:string,
  totalResults: number,
  articles: 
    {
      source: {
        id: string,
        name: string
      },
      author: string,
      title: string,
      url: string,
      imgUrl: string,
      publishedAt: string,
      content: string
    }[]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM