[英]How to specify type of index of enum in typescript
考虑以下示例:
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'.
索引变量必须是枚举 Color 键的字符串版本。 如何指定索引变量的类型?
您应该使用let index: keyof typeof Color
,因为Color
实际上是 object (各种字典),因此您需要先使用typeof
获取其类型。 对于keyof
和typeof
的作用的深入解释,有一个很好的问题和线程来解释它。
enum Color {
Green = "green",
Red = "red"
}
let index: keyof typeof Color;
index = "Green"
console.log(Color[index])
请参阅TypeScript Playground上的工作示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.