Chapter 9: Type-Level Programming
Runnable examples: examples/ch09-type-level-programming.ts
Conditional types, infer, mapped types and recursion make TypeScript’s type system a small functional programming language. This chapter shows how to use it for real utilities, and when to stop.
Tuples are lists
Variadic tuple types (TypeScript 4.0+) let you take tuples apart and build new ones:
type Head<T extends readonly unknown[]> = T extends readonly [infer H, ...unknown[]] ? H : never;
type Tail<T extends readonly unknown[]> = T extends readonly [unknown, ...infer R] ? R : [];
type Reverse<T extends readonly unknown[]> =
T extends readonly [infer H, ...infer R] ? [...Reverse<R>, H] : [];
This is the same recursion you would write over a linked list in a functional language: handle the head, recurse on the tail, stop at the empty case.
Numbers through tuple lengths
The type system has no arithmetic, but a tuple’s length is a numeric literal type:
type BuildTuple<N extends number, Acc extends unknown[] = []> =
Acc["length"] extends N ? Acc : BuildTuple<N, [...Acc, unknown]>;
type Add<A extends number, B extends number> = [...BuildTuple<A>, ...BuildTuple<B>]["length"];
type Seven = Add<3, 4>; // 7
Fun, and occasionally useful for small fixed sizes, but recursion depth limits make it impractical for large numbers.
A useful utility: typed dot paths
Configuration and form libraries often access nested values by string path. Types can make those paths checked:
type Paths<T> = T extends object
? { [K in keyof T & string]:
T[K] extends readonly unknown[] ? K
: T[K] extends object ? K | `${K}.${Paths<T[K]>}`
: K
}[keyof T & string]
: never;
type PathValue<T, P extends string> =
P extends `${infer K}.${infer Rest}`
? K extends keyof T ? PathValue<T[K], Rest> : never
: P extends keyof T ? T[P] : never;
Two techniques appear here:
- Mapped type then index:
{ [K in ...]: X }[keyof ...]builds an object of results and immediately turns it into a union of its values. - Recursive template parsing to walk a path one segment at a time.
getPath(config, "server.port"); // number
getPath(config, "server.hostname"); // Error: not a valid path
Arrays are treated as leaves on purpose; including array indices makes the union of paths much larger.
Union to intersection
type UnionToIntersection<U> =
(U extends unknown ? (arg: U) => void : never) extends (arg: infer I) => void ? I : never;
It works by putting each union member in a contravariant position (a parameter). When TypeScript infers a single type from several candidates in contravariant positions, it produces their intersection. Chapter 8 explains why parameters are contravariant.
Overloads for typed composition
Some things are simpler with overloads than with clever recursive types:
function pipe<A, B>(a: A, ab: (a: A) => B): B;
function pipe<A, B, C>(a: A, ab: (a: A) => B, bc: (b: B) => C): C;
function pipe<A, B, C, D>(a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D): D;
Each step’s input is inferred from the previous step’s output, and the callbacks need no annotations. Many functional libraries define long overload lists like this.
Testing types
This repository tests type-level code with two tools that need no library:
type Equal<A, B> =
(<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
type Expect<T extends true> = T;
type _test = Expect<Equal<Reverse<[1, 2, 3]>, [3, 2, 1]>>; // fails to compile if wrong
And // @ts-expect-error above a line that must fail to compile; if the line ever compiles, the directive itself becomes an error. npm run typecheck runs all of these assertions.
The Equal definition compares types through how they behave in a deferred conditional, which distinguishes any from other types and catches readonly differences that a simple mutual-assignability check would miss.
When to stop
Type-level code has real costs:
- Readability: teammates must understand it to change it.
- Error messages: complex types produce long, confusing errors.
- Compile time: recursive types slow down the editor and CI.
A good rule: write type-level code when it removes a whole class of bugs for many call sites (routing, forms, configuration, event systems). Prefer simple, explicit types everywhere else. When in doubt, a runtime check plus a simple type is easier to maintain.
Check yourself
- What does
{ [K in "a" | "b"]: K }["a" | "b"]evaluate to? - Why does
UnionToIntersectionproduce an intersection? - What happens to
// @ts-expect-errorif the line below it compiles without error?