【问题标题】:TypeScript enum with objects带有对象的 TypeScript 枚举
【发布时间】:2020-03-14 07:04:49
【问题描述】:

我正在尝试使用Javarome's answera previous TypeScript question 来了解如何在枚举中使用对象:

class Material {
  public static readonly ACRYLIC = new Material(`ACRYLIC`, `AC`, `Acrylic`);
  public static readonly ALUM = new Material(`ALUM`, `AL`, `Aluminum`);
  public static readonly CORK = new Material(`CORK`, `CO`, `Cork`);
  public static readonly FOAM = new Material(`FOAM`, `FO`, `Foam`);

  // private to diallow creating other instances of this type.
  private constructor(
    public readonly key: string,
    public readonly id: string,
    public readonly name: string
  ) {}

  public toString(): string {
    return this.key;
  }
}

不幸的是,当我尝试使用括号语法时,我在代码后面遇到了一个问题(因为它在 for-of 循环中):

const materials: string[] = [`ACRYLIC`, `FOAM`];
for (const materialKey of materialsArray) {
  const material: Material = Material[materialKey];
  // ...
}

这会弹出一个巨大的 TS 错误 [TS(7053)] 并显示以下消息:

元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引“typeof Material”类型。

在 'typeof Material'.ts(7053) 类型上没有找到带有 'string' 类型参数的索引签名

我已经在谷歌上搜索了几个小时,但没有发现任何帮助。有没有办法使用括号语法来引用这个“枚举”?

【问题讨论】:

    标签: typescript enums


    【解决方案1】:

    这段代码的问题正是:

    const materials: string[] = [`ACRYLIC`, `FOAM`];
    

    Material 静态类的可能属性与字符串列表之间没有关系。问题的关键是在 type 中指定我们拥有的列表是仅允许的属性列表,其值为 Material 类型。

    可以通过Exclude 类型的实用程序来实现。看看下面的例子:

    type MaterialKeys = Exclude<keyof typeof Material, 'prototype'>;
    const materialsArray: MaterialKeys[] = [`ACRYLIC`, `FOAM`];
    for (const materialKey of materialsArray) {
      const material: Material = Material[materialKey];
      // ...
    }
    

    更多信息:Exclude&lt;keyof typeof Material, 'prototype'&gt;; 将获取所有Material 类型的键并从中排除prototype,因此我们将获得所有静态字段,这就是我们想要的。

    【讨论】:

    • 您,先生,是个天才。非常感谢您的帮助!
    猜你喜欢
    • 2020-04-04
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 2021-04-06
    • 2022-09-23
    • 1970-01-01
    相关资源
    最近更新 更多