Union String Literals as Property Paths
What you'll learn: How to create type-safe nested property accessors by mapping union string literals into valid property path types.
The Pattern
Now that you can map over unions, you can combine union string literals with mapped types to generate property path types — essentially creating type-safe "dot notation" or "path strings" that represent valid paths through nested objects.
type User = {
name: string;
address: {
street: string;
city: string;
};
};
// Generate first-level paths
type Paths = keyof User; // "name" | "address"
// Generate nested paths manually
type NestedPaths = "name" | "address" | "address.street" | "address.city";
The real power comes from using mapped types to automatically generate these path strings from object structures.
Building Path Types with Mapping
type PathsToStringProps<T> = {
[K in keyof T]: T[K] extends string ? K : never
}[keyof T];
type User = {
id: number;
name: string;
email: string;
age: number;
};
// Result: "name" | "email"
type StringPaths = PathsToStringProps<User>;
This pattern maps over each key, creates a conditional that returns the key only if the property is a string, then extracts all non-never values.
Real-World Use Case: Type-Safe Path Access
type Product = {
title: string;
price: number;
category: {
name: string;
id: number;
};
};
type PropertyPaths = {
[K in keyof Product]: K
}[keyof Product];
// Result: "title" | "price" | "category"
// Use it in a getter function
function getProperty<T, K extends keyof T>(obj: T, path: K): T[K] {
return obj[path];
}
This ensures you can only pass valid property names, and the return type matches the property type automatically.
Key Takeaway: By mapping over union string literal types and using indexed access, you can generate valid property path types that provide autocomplete and type safety for nested object access patterns.