Type-Level Logic

A data-layer function getOrder(id, options) could include order lines or not, and always returned Order & { lines?: Line[] }. Callers that asked for lines had to cast or check anyway; callers that did not could still read them and get undefined.

Conditional types let a type depend on another type, so a return type can follow its input. They are powerful and easy to overdo. Below is the basic form, infer, the distributive behaviour that surprises nearly everyone once, recursive conditional types, and when plain overloads are the better choice.

If callers keep casting your return types
  • You see T extends U ? X : Y in the TypeScript source and skip past it
  • You copy infer patterns without understanding how the capture works
  • You hit the distributive behaviour by accident and get a union when you expected a single type
  • You want a type that returns different output types based on input — and don't know how to express it

Conditional types let you encode runtime branching at the type level — the basis of overloads that actually compose.