Javascript 如何在typescript中指定枚举的索引类型

Javascript 如何在typescript中指定枚举的索引类型,javascript,typescript,Javascript,Typescript,考虑以下示例: enum Color { Green = "green", Red = "red" } let index : keyof Color index = "Green" console.log(Color[index]) 错误 索引变量必须是枚举颜色键的字符串版本。 如何指定索引变量的类型?您应该使用let index:keyof typeof Color,因为Color实际上是一个对象(排序字典

考虑以下示例:

enum Color {
    Green = "green",
    Red = "red"

}

let index : keyof Color
index = "Green" 

console.log(Color[index])
错误

索引变量必须是枚举颜色键的字符串版本。
如何指定索引变量的类型?

您应该使用
let index:keyof typeof Color
,因为
Color
实际上是一个对象(排序字典),所以您需要首先使用
typeof
获取其类型。要深入解释
keyof
typeof
的功能,请参阅


请参阅上的工作示例。

可能:
let index:keyof typeof Color
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'.
enum Color {
    Green = "green",
    Red = "red"

}

let index: keyof typeof Color;
index = "Green" 

console.log(Color[index])