TypeScript · Lesson 5

Conditional Types

Type-level if/else, infer, distribution over unions, template literal types and recursive types like DeepReadonly and Paths.

4 min read

In short

  • T extends U ? X : Y is an if for types
  • infer captures part of a matched type
  • A naked type parameter distributes over unions
  • Template literal types build and parse strings
  • Recursion handles nested types, within limits

Conditional types are the if of the type system. Together with infer, template literal types and recursion they make TypeScript's type language Turing-complete, which is powerful, and also a reason to use them with restraint.

The basics

▶ Try
type IsString<T> = T extends string ? true : false;

type A = IsString<'hi'>;   // true
type B = IsString<42>;     // false

T extends U ? X : Y asks "is T assignable to U?" When T is still a generic type parameter, the conditional stays deferred until T is known, which is why a function returning T extends string ? ... : ... often needs a cast inside its body.

infer: pattern matching on types

In the extends clause you can declare a type variable with infer and TypeScript fills it in if the pattern matches:

▶ Try
type MyReturnType<F> = F extends (...args: any[]) => infer R ? R : never;
type ElementType<T> = T extends readonly (infer E)[] ? E : T;
type UnwrapPromise<T> = T extends Promise<infer V> ? V : T;

type R1 = MyReturnType<() => Date>;          // Date
type E1 = ElementType<string[]>;             // string
type U1 = UnwrapPromise<Promise<number>>;    // number

Since TS 4.7 you can constrain an inferred variable: T extends [infer Head extends string, ...unknown[]] ? Head : never. Since 4.8 infer N extends number on a template literal even parses numbers: '42' extends `${infer N extends number}` ? N : never is 42.

Built-ins you now understand: ReturnType, Parameters, ConstructorParameters, InstanceType, NonNullable, Awaited (recursive, and also unwraps any "thenable").

Distribution over unions

When the checked type is a naked type parameter, a conditional type is applied to each member of a union separately and the results are unioned:

▶ Try
type ToArray<T> = T extends unknown ? T[] : never;
type X = ToArray<string | number>;   // string[] | number[]   (not (string | number)[])

That's exactly how Exclude and Extract work:

▶ Try
type MyExclude<T, U> = T extends U ? never : T;
type Y = MyExclude<'a' | 'b' | 'c', 'a'>;  // 'b' | 'c'

To disable distribution, wrap both sides in a one-element tuple, so the checked type is no longer naked:

▶ Try
type ToArrayNonDist<T> = [T] extends [unknown] ? T[] : never;
type Z = ToArrayNonDist<string | number>;  // (string | number)[]

never is the empty union, so a distributive conditional over never returns never without evaluating either branch. That's why type IsNever<T> = T extends never ? true : false gives never for never; the correct version is [T] extends [never] ? true : false.

A real-world payoff: Omit on a discriminated union destroys it (it only keeps common keys). A distributive wrapper fixes that:

▶ Try
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;

Template literal types

Template literal types build string literal types, and they multiply out unions:

▶ Try
type Method = 'get' | 'post';
type Resource = 'user' | 'order';
type Endpoint = `${Method}:/${Resource}s`;   // 'get:/users' | 'get:/orders' | 'post:/users' | 'post:/orders'
type Handler<E extends string> = `on${Capitalize<E>}`;  // Handler<'click'> = 'onClick'

Combined with infer they parse strings:

▶ Try
type RouteParams<S extends string> =
  S extends `${string}:${infer Param}/${infer Rest}` ? Param | RouteParams<Rest>
  : S extends `${string}:${infer Param}` ? Param
  : never;

type P = RouteParams<'/users/:userId/posts/:postId'>;  // 'userId' | 'postId'

This is how Express and Hono type route parameters, and how libraries type 'user.address.city'-style paths.

Recursive types

Type aliases may refer to themselves, which handles nested structures:

▶ Try
type DeepReadonly<T> =
  T extends (...args: any[]) => any ? T
  : T extends object ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
  : T;

Because the mapped type is homomorphic, arrays become readonly arrays automatically. Functions are checked first so they aren't turned into empty objects.

Limits: TypeScript caps instantiation depth (you'll see "Type instantiation is excessively deep and possibly infinite"). Conditional types in tail position (the recursive call is the whole branch result) are optimised and may recurse about 1000 levels; others hit the limit far sooner. Accumulator parameters (type Reverse<S, Acc = ''>) keep recursion in tail position.

Gotchas

  • Assignability, not equality. T extends U is "assignable", so never extends X is always true, any takes both branches (any extends string ? 1 : 2 is 1 | 2), and { a: 1 } extends {} is true.
  • Deferred conditionals in implementations. Inside function f<T>(x: T): T extends string ? number : boolean, TypeScript can't pick a branch, so return 1 fails. Use overloads or a single cast.
  • infer in contravariant positions (function parameters) infers an intersection from multiple candidates: that's the trick behind UnionToIntersection. Fun, rarely needed.
  • Readability is a feature. A 40-line conditional type that only its author understands is a liability. Name intermediate types, add type tests (Expect<Equal<...>>), and prefer simpler APIs when possible.

In real codebases

Side note

Conditional types mostly live in library and infrastructure code: API clients (ResponseOf<Endpoint>), ORMs (Prisma's GetPayload computes result types from your select), form libraries (Path<FormValues> in React Hook Form), routers (param extraction), event systems (on${Capitalize<E>} handlers), and utility layers (DeepPartial for config overrides and test fixtures). In application code you'll mostly use them; knowing how they work is what lets you read the error messages they produce.

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app