【发布时间】:2021-06-02 01:34:03
【问题描述】:
考虑以下示例:
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'.
索引变量必须是枚举颜色键的字符串版本。 如何指定索引变量的类型?
【问题讨论】:
-
也许:
let index : keyof typeof Color
标签: javascript typescript