Map instead of an object to store key/value pairs!
This code runs fine, and yet TypeScript flags an error in it. Why?
k symbols gives a clue:
The type of
string, but you're trying to index into an object whose type only has three specific keys:
'three'. There are strings other than these three, so this has to fail.
Plugging in a narrower type declaration for
k fixes the issue:
So the real question is: why is the type of
k in the first example inferred as
string rather than
"one" | "two" | "three"?
To understand, let's look at a slightly different example involving an interface and a function:
It's the same error as before. And you can "fix" it using the same sort of declaration (
let k: keyof ABC). But in this case TypeScript is right to complain. Here's why:
foo can be called with any value assignable to
ABC, not just a value with "a," "b," and "c" properties. It's entirely possible that the value will have other properties, too (see Item 4: Get Comfortable with Structural Typing). To allow for this, TypeScript gives
k the only type it can be confident of, namely,
keyof declaration would have another downside here: