Advanced · 5 of 12 · 13 min read
Type-level programming
Conditionals, mapped types, infer and recursion combined into real computation — and the judgement about when a clever type costs more than it pays.
- Conditional types
- Mapped types
The type system is a small, pure, lazily-evaluated functional language. It has values (types),
functions (generic aliases), branching (conditionals), pattern matching (infer), iteration
(mapped types) and recursion. This lecture is about using all of it at once, and about when not to.
The vocabulary, assembled
| Programming idea | Type-level spelling |
|---|---|
| Function | type F<T> = ... |
| Argument with a bound | <T extends Constraint> |
| Default argument | <T = Fallback> |
if |
T extends U ? X : Y |
| Destructuring | infer in an extends clause |
for over keys |
{ [K in keyof T]: ... } |
| Map over a union | a distributive conditional |
| Filter a union | T extends U ? T : never |
| Head / tail | [infer Head, ...infer Tail] |
| Base case | the empty tuple, or a non-matching pattern |
| Local variable | an extra type parameter with a default |
| Accumulator | a tuple that grows through the recursion |
Recursion with an accumulator
The type system has no mutable state, so a loop counter is a tuple whose length is the count:
type Repeat<T, N extends number, Acc extends T[] = []> =
Acc["length"] extends N ? Acc : Repeat<T, N, [...Acc, T]>;
type A = Repeat<string, 3>; // [string, string, string]
const a: A = ["x", "y", "z"];
console.log(a.length);
Acc["length"] is how a tuple’s length is read as a numeric literal, and the extra parameter with
a default is the accumulator. Arithmetic follows from the same trick:
type Length<T extends readonly unknown[]> = T["length"];
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> =
Length<[...BuildTuple<A>, ...BuildTuple<B>]>;
type Three = Add<1, 2>; // 3
const three: Three = 3;
console.log(three);
It works, it is a good way to understand the machine, and it has no place in production code: the compiler is counting in unary, and it stops at about a thousand.
Deep transformations
These do have a place, and they are the most common real use:
type Primitive = string | number | boolean | bigint | symbol | null | undefined;
type DeepPartial<T> = T extends Primitive | Date | ((...args: never[]) => unknown)
? T
: T extends readonly (infer Item)[]
? readonly DeepPartial<Item>[]
: { [K in keyof T]?: DeepPartial<T[K]> };
interface Config {
server: { host: string; port: number; tags: string[] };
createdAt: Date;
}
const patch: DeepPartial<Config> = { server: { host: "x" } };
console.log(patch.server?.host);
The care is entirely in the base cases. Date, Map, RegExp and functions all satisfy
extends object, and walking into them produces a type that looks right and accepts nothing. A
deep utility without an explicit bail-out list is the most common way this goes wrong.
Extracting a union of paths
type Paths<T> = T extends object
? { [K in keyof T & string]: K | `${K}.${Paths<T[K]>}` }[keyof T & string]
: never;
interface Config {
server: { host: string; port: number };
debug: boolean;
}
type P = Paths<Config>;
// "server" | "debug" | "server.host" | "server.port"
const path: P = "server.port";
console.log(path);
The map-then-index shape again: build an object whose values are the strings, then take the union
of its values. Combined with the Get<T, Path> type from the template-literal lecture, this is a
fully typed get(config, "server.port").
Exact type equality
The naive version does not work, and knowing why is a good interview answer:
type NaiveEqual<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
type A = NaiveEqual<{ a: string }, { a: string }>; // true
type B = NaiveEqual<any, string>; // true — wrong
// The version that distinguishes `any`:
type Equal<X, Y> =
(<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
type C = Equal<any, string>; // false
type D = Equal<{ a: string }, { a: string }>; // true
const c: C = false;
const d: D = true;
console.log(c, d);
Mutual assignability is not identity, because any is assignable in both directions. The second
form compares two deferred conditional signatures, which the compiler only considers identical
when the checked types are identical — a quirk rather than a designed feature, and the basis of
every type-testing library.
That gives you compile-time tests for your own types:
type Equal<X, Y> =
(<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
type Expect<T extends true> = T;
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
interface User { id: number; name: string }
type Test = Expect<Equal<MyPick<User, "id">, { id: number }>>;
// A wrong implementation fails to compile. No test runner involved.
const test: Test = true;
console.log(test);
The limits
// type Explode<N extends number, Acc extends unknown[] = []> =
// Acc["length"] extends N ? Acc : Explode<N, [...Acc, unknown]>;
// type Boom = Explode<5000>;
// Type instantiation is excessively deep and possibly infinite.
export {};
Around 1000 instantiations deep, 100 for non-tail-recursive positions, and the failure mode is
worth internalising: the type becomes any, so everything downstream silently stops being
checked. A clever type that broke is less safe than no type at all.
Three things that make a type expensive, in order of impact:
- Cross products. Two large unions in a template literal or an intersection.
- Deep recursion over a long tuple or a long string literal.
- Large unions through a distributive conditional, which instantiates once per member.
And the mitigations: constrain parameters so the compiler can reject early, use interfaces rather than large intersections for object shapes, and give expensive computed types a name so the result is cached rather than recomputed at each use site.
When not to
The honest answer to most type-level puzzles in application code is that there is a simpler design:
| Instead of | Prefer |
|---|---|
| A deep recursive path type for one call site | an explicit interface |
| Type-level arithmetic | a runtime check, or a tuple written out |
| A 60-line conditional to infer a shape | a type parameter the caller passes |
| An exactly-typed dynamic object | a discriminated union of the real cases |
| Deriving a validator from a type | deriving the type from a validator (zod and friends) |
That last row is the one that changed most practice: a schema library infers the type from the runtime validator, so the single source of truth is the thing that actually runs. It removes most of the need for hand-written deep types in application code.
The place type-level work genuinely pays is a library boundary — a query builder, a router, a form library, an ORM — where one difficult type is written once and makes a thousand call sites safe. Inside an application, the same effort usually buys much less than a clearer interface.
Common mistakes
A deep utility without base cases
Mistake. DeepPartial<T> that maps every object.
Why it fails. Date, Map, RegExp and functions are objects; mapping their keys produces a
type that nothing satisfies.
What to do instead. Bail out on primitives and built-ins explicitly, before the mapped branch.
Mutual assignability as equality
Mistake. A extends B ? (B extends A ? true : false) : false.
Why it fails. any is assignable both ways, so it equals everything.
What to do instead. The deferred-conditional Equal, and accept it is a quirk.
Building it because it is possible
Mistake. A 40-line conditional type where a hand-written interface would do. Why it fails. It compiles slowly, breaks obscurely, and nobody else will touch it. The next feature then routes around the type rather than extending it. What to do instead. Write the simple type, and reach for the machinery only at a boundary that many call sites cross.
Check yourself
2 questions from the bank on what you just read. Answering here does not affect your quiz history.
A recursive type has to terminate, and the compiler enforces a depth limit.
What does "Type instantiation is excessively deep and possibly infinite" mean?
type Count<N extends number, Acc extends unknown[] = []> =
Acc["length"] extends N ? Acc : Count<N, [...Acc, unknown]>;
type Boom = Count<5000>;A mapped type over a union of keys does not have to come from an existing object.
What does { [K in "a" | "b"]: number } produce?
type Pair = { [K in "a" | "b"]: number };Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.