简体   繁体   中英

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. 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 . For an in-depth explanation on what keyof and typeof does, there's an excellent question and thread that explains it .

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

}

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

console.log(Color[index])

See working example on TypeScript Playground .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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