考虑以下示例:
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'.
index变量必须是枚举Color的键的字符串版本。如何指定索引变量的类型?
您应该使用let index: keyof typeof Color
,因为Color
它实际上是一个对象(各种字典),所以您首先需要使用来获取其类型typeof
。对于什么进行了深入的解释keyof
和typeof
做,有一个很好的问题和线索,解释它。
enum Color {
Green = "green",
Red = "red"
}
let index: keyof typeof Color;
index = "Green"
console.log(Color[index])
请参阅TypeScript Playground上的工作示例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句