使用 TypeScript 枚举而不是 union 作为对象键

Use TypeScript enum instead of union for object keys

提问人:meez 提问时间:9/6/2023 更新时间:9/6/2023 访问量:27

问:

我在我的 React 打字稿项目中有这个映射:

const templates = {
    TypeOne: {
      expanded: (typeOne: ItemOneType) => <ItemOne key={typeOne.id} {...typeOne} />,
    },
    TypeTwo: {
      expanded: (typeTwo: ItemTwoType) => <ItemTwo key={typeTwo.uuid} {...typeTwo} />,
    },
  };

然后我映射数组,如下所示:

  <ul>
    {items.map((item) => {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      return templates[item.type][listType](item as any);
    })}
  </ul>

我还有一个:enum

export enum TeaserTypeName {
  TypeOne = 'TypeOne',
  TypeTwo = 'TypeTwo',
}

有没有办法将上述值用于“模板”对象中的键而不是联合?enumtype: 'TypeOne' | 'TypeTwo';

reactjs typescript 对象 枚举 union-types

评论

1赞 Behemoth 9/6/2023
这种方法是你要找的吗?
0赞 jsejcksn 9/6/2023
这回答了你的问题吗?JavaScript 按变量设置对象键

答:

0赞 siwalikm 9/6/2023 #1

是的,您可以将枚举值用于模板对象中的键,而不是联合类型“TypeOne” |“类型二”。以下是修改代码的方法:

const templates = {
  [TeaserTypeName.TypeOne]: {
    expanded: (typeOne: ItemOneType) => <ItemOne key={typeOne.id} {...typeOne} />,
  },
  [TeaserTypeName.TypeTwo]: {
    expanded: (typeTwo: ItemTwoType) => <ItemTwo key={typeTwo.uuid} {...typeTwo} />,
  },
};