I'm struggling to understand the type checking errors in the code snippet below:
interface Foo {
kind: 'foo';
a: string;
}
interface Bar {
kind: 'bar';
b: number;
}
type FooBar = Foo | Bar;
interface Container {
ids: number[];
fooBar: FooBar;
}
const cont: Container = {
ids: [1, 2],
fooBar: { kind: 'foo', a: 'a' },
};
switch (cont.fooBar.kind) {
case 'foo':
console.log(cont.fooBar.a); // This line is fine
cont.ids.map((id) => {
console.log(`${id} - ${cont.fooBar.a}`);
// Getting error: Property 'a' does not exist on type FooBar nor Bar
})
break;
case 'bar':
console.log(cont.fooBar.b); // This line is also fine
cont.ids.map((id) => {
console.log(`${id} - ${cont.fooBar.b}`);
// Getting error: Property 'b' does not exist on type FooBar nor Foo
})
break;
}
For a live demonstration of this issue, check out this playground example.