[英]How to define type or interface for dynamic object?
假設我有以下代碼:
interface ItemsByKeyInterface {}
interface AType {
key: number;
label: string;
}
const array: AType[] = [
{ key: "a", label: "1" },
{ key: "b", label: "2" }
];
const itemsByKey: ItemsByKeyInterface = array.reduce((total, item) => {
return {
...total,
[item.key]: item
};
}, {});
我應該如何正確定義ItemsByKeyInterface
? 考慮 AType 可以是任何東西(任何具有 key 屬性的東西),並且數組可以有無限且未知數量的項目(考慮 key 在該數組中是唯一的)
const p = itemsByKey.b.label;
你試過這個嗎
interface ItemsByKeyInterface {
[key: number]: Item;
}
interface Item { key: number; label: "1"| "2"; } interface ItemsByKeyInterface { [key: Item["key"]]: Item; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.