简体   繁体   English

如何为动态 object 定义类型或接口?

[英]How to define type or interface for dynamic object?

Let's suppose that I have the following code:假设我有以下代码:

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
  };
}, {});

How should I define ItemsByKeyInterface properly?我应该如何正确定义ItemsByKeyInterface Consider that AType could be anything (anything with a key property) and the array could have an unlimited and unknown number of items (consider that key would be unique in that array)考虑 AType 可以是任何东西(任何具有 key 属性的东西),并且数组可以有无限且未知数量的项目(考虑 key 在该数组中是唯一的)

const p = itemsByKey.b.label;

Did you try this你试过这个吗

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM