Reputation: 1610
const fn = (condition: boolean) => condition ? {a: ""} : {b: ""}
I have trouble with understanding why return type of fn is:
{
a: string;
b?: undefined;
} | {
b: string;
a?: undefined;
}
but not
{
a: string;
} | {
b: string;
}
Upvotes: 1
Views: 577
Reputation: 51
It has to do with TypeScript's type inference – in the function fn
, there is no other context for TS to discount the possibility of either a
or b
existing in either of the conditional's scenarios, so it infers this all-encompassing type you show.
Consider:
const obj1 = {a: ""}
const obj2 = {b: ""}
const fn2 = (condition: boolean) => condition ? obj1 : obj2
The returned type of fn2
is what you proposed the type might be for fn
; this is because TS has inferred the type for the objects beforehand, in isolation.
Upvotes: 1