0Pricing
TypeScript Academy · Lesson

Type-Level Conditionals

Branch on types with conditional type expressions.

The Type-Level If

The type language gains branching with conditional types. The syntax T extends U ? X : Y reads: if T is assignable to U, the result is X, otherwise it is Y.

This is the type-level equivalent of an if / else expression.

type IsString<T> = T extends string ? "yes" : "no";

type A = IsString<string>; // "yes"
type B = IsString<number>; // "no"

extends Means Assignable

The test is not equality. T extends U is true when a value of type T could be used where a U is expected. Literal types are assignable to their base type.

type T1 = "hello" extends string ? true : false; // true
type T2 = string extends "hello" ? true : false; // false
type T3 = 42 extends number ? true : false;       // true

All lessons in this course

  1. Types as a Computation Language
  2. Type-Level Conditionals
  3. Type-Level Recursion
  4. Distributive Conditional Types
← Back to TypeScript Academy