Constructing Path Unions from Object Keys
You'll learn how to automatically generate type-safe string literals representing every valid path through a nested object structure.
What This Solves
Imagine you have a deeply nested settings object and need to create a type that represents every valid path like "user.profile.name" or "theme.colors.primary". Writing these by hand is tedious and error-prone. Template literal types combined with mapped types let you generate these path unions automatically from your object's shape.
The Core Pattern
You build path unions recursively using mapped types with template literals. For each key in an object type, you:
- Map over the keys using
keyof - Construct the current path using template literal types
- Recursively generate sub-paths for nested objects
- Union everything together to create all possible paths
Here's the basic structure:
type Paths<T> = {
[K in keyof T]: K extends string
? T[K] extends object
? `${K}.${Paths<T[K]>}` | K
: K
: never;
}[keyof T];
This type says: "For each key, if the value is an object, create both the key itself AND all nested paths prefixed with key."
Example in Action
type Config = {
user: {
profile: {
name: string;
};
age: number;
};
theme: string;
};
type ConfigPaths = Paths<Config>;
// Result: "user" | "theme" | "user.profile" | "user.age" | "user.profile.name"
The mapped type iterates over "user" and "theme", detects that user contains nested objects, and recursively builds all possible dot-notation paths.
Key Takeaway: By combining mapped types with template literals and conditional recursion, you can automatically generate unions of all valid property paths through any nested object structure, enabling type-safe path-based APIs.