← Lessons

quiz vs the machine

Platinum1820

Frontend

Conditional Types

Pick a result type based on whether one type matches another.

5 min read · advanced · beat Platinum to climb

A type level branch

A conditional type chooses between two results using the form T extends U then X else Y. It is an if statement that runs in the type system rather than at runtime.

The extends test

The check is assignability, not class inheritance. It asks whether the left type fits into the right one. If yes you get the then branch, otherwise the else branch.

Inferring with infer

Inside the extends clause you can introduce a placeholder with infer to capture part of a type. This is how a helper extracts the element type of an array or the resolved value of a promise.

Distribution over unions

When the checked type is a naked type parameter and you pass a union, the conditional distributes across each member and unions the results. Wrapping both sides in a tuple turns this distribution off when you want the union treated as a whole.

Where it earns its place

Conditional types power many library helpers. They let an API return one shape for one input and a different shape for another, all resolved before any code runs.

Key idea

A conditional type branches on assignability, can capture pieces with infer, and distributes over unions unless you suppress it.

Check yourself

Answer to earn rating on the learn ladder.

1. What does the extends keyword test in a conditional type?

2. What does infer let you do inside an extends clause?