Recursive Path Types for Deep Objects
You'll learn: How to build a type that generates all valid dot-notation paths through a nested object structure using recursive template literal types.
What This Solves
Imagine you have a deeply nested configuration object, and you want TypeScript to autocomplete and validate paths like "user.address.city" or "settings.theme.colors.primary". You need a type that traverses the entire object tree and generates every possible path as a string literal union.
The Recursive Pattern
A recursive path type uses conditional types to inspect each property. For primitive values, it returns the current key. For nested objects, it recurses by:
- Iterating over keys with a mapped type
- Generating child paths recursively
- Joining parent and child keys with a template literal (
.) - Combining all possibilities into a union
Core Structure
type DeepPath<T> = T extends object
? {
[K in keyof T]: K extends string
? T[K] extends object
? K | `${K}.${DeepPath<T[K]>}`
: K
: never;
}[keyof T]
: never;
How it works:
- The mapped type iterates each key
K - For primitives: just return
K(the key itself) - For nested objects: return both
KandK.childPathrecursively - The
[keyof T]index access collects all branches into a union
Example Usage
type Config = {
user: {
name: string;
address: {
city: string;
zip: number;
};
};
theme: {
mode: string;
};
};
type Paths = DeepPath<Config>;
// Result: "user" | "user.name" | "user.address" |
// "user.address.city" | "user.address.zip" |
// "theme" | "theme.mode"
This enables type-safe path-based APIs like getValue(config, "user.address.city") with full autocomplete.
Key Takeaway: Recursive template literal types combine mapped types, conditional checks, and string concatenation to traverse object structures and generate all valid dot-notation paths as a compile-time union.