I have the following typescript code which uses a discriminated union to distinguish between some similar objects:
interface Fish {
type: 'FISH',
}
interface Bird {
type: 'BIRD',
flyingSpeed: number,
}
interface Ant {
type: 'ANT',
}
type Beast = Fish | Bird | Ant
function buildBeast(animal: 'FISH' | 'BIRD' | 'ANT') {
const myBeast: Beast = animal === 'BIRD' ? {
type: animal,
flyingSpeed: 10
} : {type: animal}
}
In the function buildBeast it accepts a string that complies with all possible types of my Beast type, yet it does not allow me to declare the myBeast as type Beast due to this error:
Type '{ type: "BIRD"; flyingSpeed: number; } | { type: "FISH" | "ANT"; }' is not assignable to type 'Beast'.
Type '{ type: "FISH" | "ANT"; }' is not assignable to type 'Beast'.
Type '{ type: "FISH" | "ANT"; }' is not assignable to type 'Ant'.
Types of property 'type' are incompatible.
Type '"FISH" | "ANT"' is not assignable to type '"ANT"'.
Type '"FISH"' is not assignable to type '"ANT"'.
It seems that all cases still yield a correct Beast yet TS seems to have trouble coercing the different types. Any ideas?