Мне кажется, что typescript не распознает размеченные типы объединения, если они предоставлены без какой-либо аннотации типа. Я что-то упускаю ? Есть ли какая-то причина для этого?
export type Stuff = AType | BType
export type AType = { status: Kind.A; name: string }
export type BType = { status: Kind.B; quantity: number }
export enum Kind {
A,
B,
}
function PlayWithStuff(stuff: Stuff) {
console.log('some stuff', stuff)
}
const stuff = {
status: Kind.B,
quantity: 2,
}
PlayWithStuff(stuff)
// ^^^^^
// Argument of type '{ status: Kind; quantity: number; }' is not assignable to parameter of type 'Stuff'.
// Type '{ status: Kind; quantity: number; }' is not assignable to type 'BType'.
// Types of property 'status' are incompatible.
// Type 'Kind' is not assignable to type 'Kind.B'.
const secondStuff: Stuff = {
status: Kind.B,
quantity: 2,
}
PlayWithStuff(secondStuff)
// OK, the type annotation on `secondStuff` fixes the problem