1. Concept library
  2. JavaScript & TypeScript
  3. Module 10: Utility and mapped types

Concept

Conditional types

A extends B ? X : Y chooses a type based on another type. With infer it can pull a piece out of a type, such as the element type of an array or the resolved type of a promise.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain how A extends B ? X : Y chooses a type
  2. Write a conditional type that uses infer to pull out an element or resolved type
  3. Predict the result of a conditional type applied to a union

In practice

A few lines that show Conditional types doing its job.

TypeScript
type Unwrap<T> = T extends Promise<infer U> ? U : T;
type A = Unwrap<Promise<number>>;    // number
type B = Unwrap<string>;             // string

type ElementOf<T> = T extends readonly (infer E)[] ? E : never;
type C = ElementOf<string[]>;        // string

type NonNullish<T> = T extends null | undefined ? never : T;

The common mistake

Watch for

Forgetting that a conditional type distributes over a union: Unwrap<Promise<A> | B> is A | B. Wrap the checked type in a tuple, [T] extends [...], when you do not want that.

What to know first

Your roadmap puts these before Conditional types, unless you already know them.

How it stays learned

Once a session shows you understand Conditional types, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled
Previous in the module← Mapped types