Advertisement
Advanced TypeScript, Template Literal Types

How would you implement a type-safe 'path getter' utility (like lodash's get()) using recursive template literal types to validate dot-separated property paths?

Short answer

Recursively split the dot-separated path string literal type using 'infer' to peel off one segment at a time, checking at each step that the segment is actually a valid key of the CURRENT nested object type, and recursing into that property's type for the next segment —…

Save TypeScript mock interview
Advertisement
AModel answer
Recursively split the dot-separated path string literal type using 'infer' to peel off one segment at a time, checking at each step that the segment is actually a valid key of the CURRENT nested object type, and recursing into that property's type for the next segment — producing full compile-time validation of arbitrarily deep property paths.
type PathValue<T, Path extends string> =
  Path extends `${infer Key}.${infer Rest}`
    ? Key extends keyof T
      ? PathValue<T[Key], Rest>
      : never
    : Path extends keyof T
      ? T[Path]
      : never;

interface State { user: { profile: { name: string } } }
type NameType = PathValue<State, 'user.profile.name'>; // string
type BadType = PathValue<State, 'user.profile.age'>;   // never -- 'age' doesn't exist
Real-world example
Building a fully type-safe deep-property-access utility that catches invalid dot-path typos at compile time, unlike lodash's untyped runtime-only get().
Likely follow-ups
  • Why does this kind of deeply recursive type-level parsing sometimes hit the TypeScript compiler's recursion depth limits on very large object types?
Related topics