typescript / expert
Snippet
Deep Nested Property Path Type Extraction
This snippet demonstrates compile-time template literal type recursions to derive dot-notated string paths for deeply nested object structures. It provides complete type safety when reading deeply nested object values, ensuring that only valid property paths are passed and that the return type accurately matches the targeted inner property.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
type Primitive = string | number | boolean | bigint | symbol | null | undefined;type PropertyPath<T> = T extends Primitive? never: {[K in keyof T & (string | number)]: T[K] extends Primitive? `${K}`: `${K}` | `${K}.${PropertyPath<T[K]>}`;}[keyof T & (string | number)];type PathValue<T, P extends string> = P extends `${infer Head}.${infer Tail}`? Head extends keyof T? PathValue<T[Head], Tail>: never: P extends keyof T? T[P]: never;function getDeepValue<T, P extends PropertyPath<T>>(obj: T, path: P): PathValue<T, P> {const keys = (path as string).split('.');let current: any = obj;for (const key of keys) {current = current?.[key];}return current;}
Breakdown
1
type PropertyPath<T> = T extends Primitive
Checks if the target type is a primitive value to terminate recursive path exploration.
2
: `${K}` | `${K}.${PropertyPath<T[K]>}`;
Constructs template literal strings recursively by joining property keys with dots.
3
type PathValue<T, P extends string> = P extends `${infer Head}.${infer Tail}`
Uses conditional infer keyword to split string paths by dot and recursively resolve the inner property type.
4
function getDeepValue<T, P extends PropertyPath<T>>(obj: T, path: P): PathValue<T, P>
Constrains the path parameter to valid PropertyPath union values and types the output via PathValue.