I've been playing with typescript discrimination using tagged union types and I've run into something odd. If I switch on the actual object property everything works as expected. But if I use destructuring, typescript reports an error. I assume it has to do with how destructuring actually works when its compiled, but I don't know for certain. You can see this sample code on the playground
interface Foo {
discriminate: 'FOO';
details: string;
}
interface Bar {
discriminate: 'BAR';
numbers: number;
}
type FooOrBar = Foo|Bar;
const foo : Foo = {
discriminate: 'FOO',
details: 'Blah Blah Blah'
}
const breakTaggedUnionWithRest = ({discriminate, ...fooBar} : FooOrBar) => {
switch(discriminate) {
case 'FOO':
console.log(fooBar.details);
break;
}
}
interface Foo2 {
discriminate: 'FOO2';
details: string;
}
interface Bar2 {
discriminate: 'BAR2';
details: number;
}
type FooOrBar2 = Foo2|Bar2;
const breakTaggedUnionWithoutRest = ({discriminate, details} : FooOrBar2) => {
switch(discriminate) {
case 'FOO2' : return details.toLowerCase();
}
}
const workingExample = (fooOrBar: FooOrBar) => {
switch(fooOrBar.discriminate) {
case 'FOO': return fooOrBar.details;
}
}
const workingExample2 = (fooOrBar: FooOrBar2) => {
switch(fooOrBar.discriminate) {
case 'FOO2': return fooOrBar.details.toString;
}
}