I'm puzzled as to why the type guard is not working in the example provided below...
Considering the following interfaces:
interface ParamA {
name: 'A';
aaa: boolean;
}
interface ParamB {
name: 'B';
bbb: number;
}
Working Properly
function func(param: ParamA | ParamB) {
switch (param.name) {
case 'A':
const aaa = param.aaa;
console.log(aaa); // boolean
break;
case 'B':
const bbb = param.bbb;
console.log(bbb); // number
break;
default:
break;
}
}
Not Working Properly
function func(param: ParamA | ParamB) {
const name = param.name; // just rewrite here
switch (name) {
case 'A':
const aaa = param.aaa;
console.log(aaa);
break;
case 'B':
const bbb = param.bbb;
console.log(bbb);
break;
default:
break;
}
}
The compiler throws errors like
Property 'aaa' does not exist on type 'ParamB'.
I fail to see why there would be a difference in behavior depending on whether it's stored in a variable or accessed directly.
This code is using TypeScript version 2.8.3.
Could someone shed some light on this issue?