Typescript ternary operation with assigment

Viewed 76
1 Answers

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

Related