带有对象的TypeScript枚举
我正在尝试使用以了解如何在枚举中使用对象:带有对象的TypeScript枚举,typescript,enums,Typescript,Enums,我正在尝试使用以了解如何在枚举中使用对象: 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`, `Co
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
循环中):
这会弹出一个巨大的TS错误[TS(7053)],并显示以下消息:
元素隐式具有“any”类型,因为类型为“string”的表达式不能用于索引类型为“typeof Material”
在类型“typeof Material”上未找到参数类型为“string”的索引签名。ts(7053)
我在谷歌上搜索了几个小时,但没有找到任何有用的东西。是否有任何方法可以使用括号语法引用此“枚举”?此代码的问题正是:
const materials: string[] = [`ACRYLIC`, `FOAM`];
Material
静态类的可能属性与字符串列表之间没有关系。问题的关键是在类型中指定,我们拥有的列表是一个仅允许属性的列表,这些属性的值为Material
type
它可以通过类型实用程序来实现。请看下面的示例:
type MaterialKeys = Exclude<keyof typeof Material, 'prototype'>;
const materialsArray: MaterialKeys[] = [`ACRYLIC`, `FOAM`];
for (const materialKey of materialsArray) {
const material: Material = Material[materialKey];
// ...
}
类型MaterialKeys=排除;
const materialsArray:MaterialKeys[]=[`ACRYLIC`、`FOAM`];
for(材质数组的常量materialKey){
常数材料:材料=材料[材料键];
// ...
}
有关更多信息:
Exclude
将使用材质的所有键
类型,并从中排除原型
,因此我们最终将拥有所有静态字段,这就是我们想要的。先生,您是一个天才。非常感谢你的帮助!
type MaterialKeys = Exclude<keyof typeof Material, 'prototype'>;
const materialsArray: MaterialKeys[] = [`ACRYLIC`, `FOAM`];
for (const materialKey of materialsArray) {
const material: Material = Material[materialKey];
// ...
}