Suppose I have this code:
const items = {
A: { x: 0 },
B: { y: 0 },
C: { z: 0 },
}
type Items = typeof items;
function foo<K extends keyof Items>(key: K, value: Items[K]) {}
This allows us to correctly enforce the type of parameters:
foo('A', { x: 0 }) // good
foo('A', { y: 0 }) // error
But how can I "assert" the type of generic parameter (or how to use some kind of type guard) when I'm inside foo
?
function foo<K extends keyof Items>(key: K, value: Items[K]) {
if (key === 'A') {
// theoretically, if K is 'A', then Items[K] must be { x: 0 }
const bar = value.x // But actually, it's error
}
}
As you might have noticed, you have to destructure
const [key, value]...
after condition, not before. Otherwise, TS is unable to bindkey, value
with the union type.