考虑以下示例:
enum Color {
Green = "green",
Red = "red"
}
let index : keyof Color
index = "Green"
console.log(Color[index])
错误
Type '"Green"' is not assignable to type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | ... 27 more ... | "padEnd"'.
Element implicitly has an 'any' type because expression of type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | ... 27 more ... | "padEnd"' can't be used to index type 'typeof Color'. No index signature with a parameter of type 'number' was found on type 'typeof Color'.
索引变量必须是枚举颜色键的字符串版本。 如何指定索引变量的类型?
答案 0 :(得分:2)
您应该使用 let index: keyof typeof Color
,因为 Color
实际上是一个对象(各种字典),因此您需要首先使用 typeof
获取其类型。要深入了解 keyof
和 typeof
的作用,请参阅 an excellent question and thread that explains it。
enum Color {
Green = "green",
Red = "red"
}
let index: keyof typeof Color;
index = "Green"
console.log(Color[index])
参见 TypeScript Playground 上的工作示例。