简体   繁体   English

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

[英]How to specify type of index of enum in typescript

Consider the following example:考虑以下示例:

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

}

let index : keyof Color
index = "Green" 

console.log(Color[index])

Error错误

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'.

The index variable has to be string version of keys of enum Color.索引变量必须是枚举 Color 键的字符串版本。 How do I specify the type of index variable?如何指定索引变量的类型?

You should be using let index: keyof typeof Color , because Color is actually an object (a dictionary of sorts), so you will need to get its type first using typeof .您应该使用let index: keyof typeof Color ,因为Color实际上是 object (各种字典),因此您需要先使用typeof获取其类型。 For an in-depth explanation on what keyof and typeof does, there's an excellent question and thread that explains it .对于keyoftypeof的作用的深入解释,有一个很好的问题和线程来解释它

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

}

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

console.log(Color[index])

See working example on TypeScript Playground .请参阅TypeScript Playground上的工作示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM