piby180
piby180

Reputation: 388

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?

Upvotes: 1

Views: 1036

Answers (1)

Terry
Terry

Reputation: 66173

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.

Upvotes: 3

Related Questions