![](/img/trans.png)
[英]How to make a structure interface that return a response with status and json.?
[英]How to structure a Typescript Interface for this Firebase Response JSON?
我有這個 JSON 響應從 Firebase 返回
{ "-KD8Evk7TULU6t6zxMHl": { "createdAt": 1458296568840, "isActive": true, "title": "...add a title", "updatedAt": 1458296568840 } }
問題的第 1 部分:我應該如何為上述 JSON 構建我的 Typescript 接口? 例如,像下面這樣?
export interface Hero {
[id: string]: {
createdAt: number;
isActive: boolean;
title: string;
updatedAt: number;
}
}
問題的第 2 部分:我應該如何使用推薦的 Typescript 接口結構獲取英雄的頭銜或 ID? 例如我想顯示英雄id和英雄頭銜
<html>
...omitted code for simplicity. I want to display hero id and title below.
<h1> {{ hero.id }} </h1>
<h1> {{ hero.title }} </h1>
</html>
您可以使用這種方式或構建一個具有另一個屬性“keyId”的類,該屬性將存儲從 firebase 響應對象(“-KD8Evk7TULU6t6zxMHl”)收到的 ID。 在構造函數中,您應該使用收到的 id 填充 keyId 道具。 不過它有點復雜,需要為每個 json 行創建一個新類。
如果你堅持你的選項 1,那么你必須使用 "Object" 類從你的對象中讀取 -> hero[Object.keys(hero)[0]].title 或者只是 Object.keys(hero)[0] 如果你想要身份證。 這有點煩人,但我看不到另一種方式,除非您像我之前提到的那樣將接口更改為帶有構造函數的類,然后您可以使用 hero[hero.keyId].title 或 hero.keyId 之類的東西作為 id ; )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.