Does type narrowing with the in
operator only work for literals or am I missing something?
Help me understand why this is happening please.
interface A {
a: string;
}
interface B {
b: number;
}
// This narrows the type correctly to A
function test(arg: A | B): string {
if ('a' in arg) {
return arg.a;
}
return arg.b.toFixed(2);
}
// This doesn't
function test2(arg: A | B): string {
let a = 'a';
if (a in arg) {
return arg.a;
}
return arg.b.toFixed(2);
}
Regarding to docs
So, I'd willing to bet it works only with literals
Workarounds