Recursive Conditional Types
February 9, 20261 min readpart 08/20
Difficulty: Advanced. Prerequisites: Conditional types, generics, infer keyword, tuples.
Recursive conditional types allow you to define types that reference themselves, enabling complex type transformations that operate on nested structures of arbitrary depth. This technique is essential for working with deeply nested objects, tree structures, and implementing utility types like DeepPartial and DeepReadonly.
Key concepts
- Self-referential type definitions
- Base cases to terminate recursion
- TypeScript's recursion depth limits (~50 levels)
- Tail-call optimization patterns
- Common patterns: DeepPartial, DeepReadonly, Flatten, Awaited
Example
// Deep Partial - makes all nested properties optional
type DeepPartial<T> = T extends object ? { [P in keyof T]?: DeepPartial<T[P]> } : T;
// Flatten nested arrays
type Flatten<T> = T extends Array<infer U> ? Flatten<U> : T;
// Reimplements the built-in Awaited (TS 4.5+)
type MyAwaited<T> = T extends Promise<infer U> ? MyAwaited<U> : T;
// Usage
type Nested = { a: { b: { c: string } } };
type DP = DeepPartial<Nested>; // { a?: { b?: { c?: string } } }
type Flat = Flatten<number[][][][]>; // number
type Res = MyAwaited<Promise<Promise<string>>>; // string
// Tail-call optimization with accumulator
type Reverse<T extends any[], Acc extends any[] = []> =
T extends [infer H, ...infer R] ? Reverse<R, [H, ...Acc]> : Acc;
type Rev = Reverse<[1, 2, 3]>; // [3, 2, 1]
// Deep Readonly
type DeepReadonly<T> = T extends object
? { readonly [P in keyof T]: DeepReadonly<T[P]> } : T;
// Collect all paths
type Paths<T, P extends string = ''> = T extends object
? { [K in keyof T & string]: `${P}${K}` | Paths<T[K], `${P}${K}.`> }[keyof T & string]
: never;
// Real-world: type-fest's ReadonlyDeep cascades over Maps, Sets, tuples, arrays
type ReadonlyDeep<T> = T extends Map<infer K, infer V>
? ReadonlyMap<ReadonlyDeep<K>, ReadonlyDeep<V>>
: T extends Set<infer U> ? ReadonlySet<ReadonlyDeep<U>>
: T extends object ? { readonly [P in keyof T]: ReadonlyDeep<T[P]> } : T;Resources
- TypeScript Handbook - Conditional Types: Official documentation
- Type-Level TypeScript: Recursive types chapter
Practice
- Deep Readonly (TypeHero, Medium)
- Flatten (TypeHero, Medium)
- Flatten Depth (TypeHero, Medium)
- Deep Readonly (Type Challenges, Medium)
- Flatten (Type Challenges, Medium)
- Flatten Depth (Type Challenges, Medium)
- Vue Basic Props (Type Challenges, Hard)
- DeepPick (Type Challenges, Hard)
Hints
- Always define a base case to prevent infinite recursion — check if T extends a primitive.
- TypeScript has a ~50-level recursion limit; use tail-call patterns for deeper recursion.