Deep Object Path Extraction with TypeScript Template Literal Types and Recursive Generics
How to build type-safe lodash.get paths, nested form dot-notation keys, and compile-time property resolvers.
When working with deeply nested configuration objects, reactive form state, or i18n translation keys, developers frequently access properties via dot-notation string paths (such as `"user.address.postalCode"`). In plain JavaScript, typos in path strings fail silently at runtime. By combining TypeScript template literal types with recursive conditional types, we can infer all valid nested object paths at compile time and accurately deduce the return type of any nested property.
THE PRODUCTION PROBLEM STATEMENT
Passing unchecked string keys to nested getter functions (`get(data, "user.ad dress.city")`) bypasses type safety, leading to `undefined` runtime exceptions in production.
Building the Recursive Path<T> Type
To generate all valid dot-separated paths of an object, we recursively iterate over the object’s keys. For each key, if the corresponding value is an object, we generate `${K}.${Path<Value>}` alongside `K`.
To prevent infinite recursion on self-referential or excessively deep types, we include a depth limiter.
// Recursive nested dot-notation path generator
export type NestedKeyOf<T> = T extends object
? {
[K in keyof T & (string | number)]: T[K] extends object
? `${K}` | `${K}.${NestedKeyOf<T[K]>}`
: `${K}`;
}[keyof T & (string | number)]
: never;
// Resolving the exact return type for a given path
export type PathValue<T, P extends string> =
P extends `${infer Key}.${infer Rest}`
? Key extends keyof T
? PathValue<T[Key], Rest>
: never
: P extends keyof T
? T[P]
: never;
// Type-safe getter function
export function getNestedProperty<T extends object, P extends NestedKeyOf<T>>(
obj: T,
path: P
): PathValue<T, P> {
const parts = (path as string).split('.');
let current: any = obj;
for (const part of parts) {
if (current == null) return undefined as any;
current = current[part];
}
return current;
}
// Example Usage:
interface UserProfile {
id: string;
account: {
settings: {
darkMode: boolean;
language: string;
};
};
}
declare const profile: UserProfile;
// ✅ Autocompletes "id", "account", "account.settings", "account.settings.darkMode", etc.
const isDark = getNestedProperty(profile, 'account.settings.darkMode');
// typeof isDark is strictly boolean![PROBABLE CAUSE] The object interface contains circular references (e.g. parent references child which references parent).
[VERIFIED RESOLUTION] Add a tuple-based depth counter or exclude circular classes with a conditional constraint.
Frequently Asked Questions & Technical Inquiries
Direct, practical answers to common architectural and debugging questions.
Yes! By typing `K in keyof T & (string | number)`, array numeric indices are automatically incorporated into the template string.
Faisal Askari
Verified AuthorSoftware Engineer & Full-Stack Developer
Faisal Askari is a software engineer with deep expertise in web systems architecture, the JavaScript runtime ecosystem, and client-side performance engineering. Over years of hands-on production engineering, he has designed and shipped enterprise dashboards, high-converting digital interfaces, and specialized full-stack applications.
Mastering Advanced TypeScript: Discriminated Unions, Type Narrowing, and Conditional Inference
A practical guide to building zero-runtime-cost type architectures using distributive conditional types, template literals, custom type guards, and exhaustive pattern matching.
TypeScript satisfies Operator vs Type Annotations: Preserving Literal Types and Narrow Contracts
A practical deep dive into bottom-up validation, preventing type widening, and retaining exact autocompletion across configuration objects.