1

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?

piby180
  • 388
  • 1
  • 6
  • 18

1 Answers1

2

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.

Terry
  • 63,248
  • 15
  • 96
  • 118