×

typescript · level 3 · unit 4 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A is an if for types.

T extends string ? "text" : "other" reads like a question: does T fit inside string? If yes, the type after the ? is the answer. If not, the type after the : is. This is a conditional type, and the checker answers it before the code runs.

Here extends means fits inside, as it does in a constraint. Answers can hold more questions, like a chain of else if. Conditional types shine in generics, where the answer depends on what the caller passes in.

type Kind<T> = T extends string ? "text" : T extends number ? "number" : "other";
const a: Kind<string> = "text";
const b: Kind<number> = "number";
const c: Kind<boolean> = "other";
console.log(a, b, c);

Read ? as “then” and : as “otherwise”.