jmk
jmk

Reputation: 1610

Typescript ternary operation with assigment

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;
}

https://www.typescriptlang.org/play?ts=4.3.5#code/FAYw9gdgzgLgBAMwnAvHAFOCATAljXSALjgCMwwAbAUwEMIBKVAPjizwMjgH44BvWiQBEQgL5wSfUsLHAgA

Upvotes: 1

Views: 577

Answers (1)

Stu Behan
Stu Behan

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.

Typescript.org/play example

Typescript Docs Inference

Upvotes: 1

Related Questions