Lesson 2.3

Conditional and mapped types

A conditional type chooses between two results based on an assignability test, which is how the built-in helpers pick apart function and promise types.

4mIntermediate18.4k students

Overview

Types that compute

A conditional type chooses between two results based on an assignability test, which is how the built-in helpers pick apart function and promise types. A mapped type walks the keys of an object type and rewrites each property, which is how readonly and optional variants are produced.

Conditionals distribute over unions by default: applied to a union, the test runs per member and the results are unioned back. That is usually what you want, and when it is not, wrapping both sides in a tuple suppresses it.

Combine the two with key remapping and you can derive an event-handler type from a state shape, or a partial update type from a record, with no duplication.

In this lesson you will:

  • Branch on a type with a conditional
  • Transform every property with a mapped type
  • Understand distribution over unions

Resources

Previous Lesson
Next Lesson
Conditional and mapped types — TypeScript Deep Dive — Vertex