【问题标题】:How to define type or interface for dynamic object?如何为动态对象定义类型或接口?
【发布时间】:2019-11-12 19:38:15
【问题描述】:

假设我有以下代码:

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;

【问题讨论】:

    标签: typescript


    【解决方案1】:

    你试过了吗

    interface ItemsByKeyInterface {
      [key: number]: Item;
    }
    

    【讨论】:

    • 我希望能够写出类似'const p = itemsByKey.b.label;'的东西。是否可以定义一个接口来做到这一点?
    猜你喜欢
    • 1970-01-01
    • 2021-03-26
    • 2021-12-08
    • 2017-01-08
    • 2022-12-05
    • 2022-01-17
    • 1970-01-01
    • 2016-12-28
    • 2021-07-06
    相关资源
    最近更新 更多