I'm trying to use discriminated union type in TypeScript but I'm getting the following error:
Type '{ data: Aaaa | Bbbb; type: "aaaa" | "bbbb"; }' is not assignable to type 'EventData'.
Type '{ data: Aaaa | Bbbb; type: "aaaa" | "bbbb"; }' is not assignable to type '{ type: "bbbb"; data: Bbbb; }'.
Types of property 'type' are incompatible.
Type '"aaaa" | "bbbb"' is not assignable to type '"bbbb"'.
Type '"aaaa"' is not assignable to type '"bbbb"'.
With the following code:
export type Aaaa = {
aPropForA: string
}
export type Bbbb = {
somePropsB: number
}
export type EventData =
| { type: 'aaaa'; data: Aaaa }
| { type: 'bbbb'; data: Bbbb }
// simulate getting the data for brevity
declare const data: EventData['data'];
declare const type: EventData['type'];
export const getEventData = (): EventData => {
return { // why is there an error?
data,
type,
}
}
What's the source of the problem? How can I fix it without typecasting?