I'm converting one of my JavaScript apps to TypeScript and I've got a problem: I've got a numeric enum, AnswerKeys and a key, "C". I'd like to get the member's value, "2", so I tried using AnswerKeys[key].
enum AnswerKeys {
'A' = 0,
'B',
'C',
}
let key = 'C'
let answer = AnswerKeys[key]
// it should log 2
console.log(answer)
It would work but I receive the following TypeScript error:
Element implicitly has an 'any' type because index expression is not of type 'number'.
It seems it has a problem with key not being a number. Other answers suggested adding as any assertion or just adding "suppressImplicitAnyIndexErrors": true to the config file, and while these do suppress the error, it's not what I want.
The following works but accepts any key and I only want to accept strings:
let answer = AnswerKeys[key as any]
I also tried keyOf AnswerKeys but it results in an extra error:
enum AnswerKeys {
'A' = 0,
'B',
'C',
}
let key: keyof AnswerKeys = 'C'
let answer = AnswerKeys[key]
console.log(answer)
Type '"C"' is not assignable to type '"toString" | "toFixed" | "toExponential" | "toPrecision" | "valueOf" | "toLocaleString"'.(2322)
Is there any way to annotate it correctly?
keyto change? If not, you can writeconst key = "C"and it works. If you're looking for an annotation, you could writekeyof typeof AnswerKeysand notkeyof AnswerKeys(which is different), and that works too. Which one are you looking for? I'm happy to write up either version as an answer.const keydoes work, butkeyis actually a parameter, it's not in the question because I tried to simplify it. It started asfunction func(key: string) {...}and I received the error mentioned above. It seemsfunction func(key: keyof typeof AnswerKeys) {is what I'm looking for. Thank you!typeof AnswerKeys[AnswerKeys]doesn't work? Or, in other words, why does TS implement reverse mapping for numeric enums but hide the related type information?