I’m trying to understand what’s wrong in this code and why TypeScript doesn’t narrow type for ‘value’ argument.
function foo<T>(data: T, cb: (key: keyof T, value: T[typeof key]) => void): void {}
foo(
{
a: true,
b: 'abc',
},
(key, value) => {
switch (key) {
case 'a':
key; // <= "a"
value; // <= string | boolean
// but I expect boolean here
}
},
);
You can see that type guard for ‘key’ variable works perfectly but ‘value’ still remains non-narrowed. Can I make ‘value’ type based on ‘key’ type?
For example:
if (key === 'b') {
value; // <= string
}
It looks like simple logic and nothing complex. Is it possible with current TypeScript?
TS version 5.6.2.
I have tried many combinations of generics and their inheritance. Nothing works and looks like TypeScript just can’t do this…?
Artem Batura is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.