代码段:
enum Color {
RED = 0,
GREEN
}
const myMap = new Map<Color, string>([
[Color.GREEN, "foo"],
[Color.RED, "bar"]
])
const red_s = "RED"
const myColor: Color = red_s as unknown as Color
console.log(`myColor ${myColor}`)
const mapVal = myMap.get(myColor)
if (mapVal) {
console.log(`mapVal ${mapVal}`)
}
else {
console.log(`no mapVal found`)
}
为什么在myMap
中找不到枚举myColor
?
如何将枚举用作映射的键?
as
关键字仅告诉编译器将变量视为特定类型。它实际上并没有改变基础类型。如果你运行一种类型的检查,你会看到myColor是一个字符串,而不是Color:
const red_s = "RED"
const myColor: Color = red_s as unknown as Color
console.log(`${typeof myColor}`) // Prints string
要将red_s设置为枚举,您需要执行以下操作:
const red_s: Color = Color["RED"];