typescript / expert
Snippet
Deep Nested Property Access Path Resolution via Recursive Template Literals
This snippet implements compile-time depth-first recursive type extraction using Template Literal Types. `Path<T>` builds a string literal union of all valid dot-separated keys, preventing invalid property string lookups. `DeepGet<T, P>` parses the path at compile time using string pattern matching (`infer`), resolving the exact target property type without manual runtime type casting.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
type Path<T> = T extends object? { [K in keyof T & (string | number)]: K extends string ? `${K}` | `${K}.${Path<T[K]>}` : never }[keyof T & (string | number)]: never;type DeepGet<T, P extends string> = P extends `${infer K}.${infer Rest}`? K extends keyof T ? DeepGet<T[K], Rest> : never: P extends keyof T ? T[P] : never;interface Configuration {database: { connection: { host: string; port: number } };}function getNestedConfig<T extends object, P extends Path<T>>(obj: T, path: P): DeepGet<T, P> {return path.split('.').reduce((acc: any, key) => acc?.[key], obj);}const config: Configuration = { database: { connection: { host: "localhost", port: 5432 } } };const port = getNestedConfig(config, "database.connection.port");
Breakdown
1
type Path<T> = T extends object ? { [K in keyof T & (string | number)]: K extends string ? `${K}` | `${K}.${Path<T[K]>}` : never }[keyof T & (string | number)] : never;
Recursively builds a union of dot-notated property paths available on object type T.
2
type DeepGet<T, P extends string> = P extends `${infer K}.${infer Rest}` ? K extends keyof T ? DeepGet<T[K], Rest> : never : P extends keyof T ? T[P] : never;
Uses template literal pattern matching with infer to recursively navigate the object type structure along path P.
3
function getNestedConfig<T extends object, P extends Path<T>>(obj: T, path: P): DeepGet<T, P>
Constrains input path P to valid path strings and maps the return type to the precisely inferred type at that path.