export enum r {
color1 = "Red"
color2 = "green"
color3 = "blue"
}
ar = ["color1", "color2"];
ar.map(e => {
if (r[e as any] !== undefined) {
return r[e]
}
})
上面的语句给出“元素隐式具有任何类型,因为索引表达式不是数字类型”
您需要输入
ar
和 keyof typeof
让 TypeScript 知道您的数组包含枚举中的键:
export enum r {
color1 = "Red",
color2 = "green",
color3 = "blue",
}
const ar: (keyof typeof r)[] = ["color1", "color2"];
const newVal = ar.map((e) => {
if (r[e] !== undefined) {
return r[e];
}
});
这里有一个很好的深入答案关于它
枚举中的每个项目后面都没有逗号。但是,以下是如何将参数类型转换为枚举的键类型:
export enum r {
color1 = "Red",
color2 = "green",
color3 = "blue",
}
const ar = ["color1","color2"];
const new_ar = ar.filter(e => {
if (e in r && r[e as keyof typeof r])
{return true;}
else {return false;}
})
您的方法的问题是您正在使用地图,并且您需要在每次迭代中返回。你需要的是过滤器。