【发布时间】:2020-03-14 07:04:49
【问题描述】:
我正在尝试使用Javarome's answer 到a 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