~/alexsh.blog

$ cat advanced-typescript/15-deep-path-types-and-dot-notation-access.md

Deep Path Types and Dot Notation Access

February 9, 20261 min readpart 15/20

Difficulty: Advanced. Prerequisites: Template literal types, recursive types, mapped types, conditional types.

Deep path types allow you to express paths into nested objects using dot notation strings (like "user.address.city") and retrieve the types at those paths. This pattern powers type-safe form libraries, ORM query builders, and lodash's get/set functions.

Key concepts

  • Generating all valid path strings for a nested object type
  • Extracting the type at a given path
  • Recursive template literal types for dot-notation
  • Type-safe get function with path autocomplete

Example

codets
// Get all paths
type Paths<T, P extends string = ''> = T extends object
  ? { [K in keyof T & string]: `${P}${K}` | Paths<T[K], `${P}${K}.`> }[keyof T & string]
  : never;

// Get type at path
type PathValue<T, P> = P extends `${infer K}.${infer R}`
  ? K extends keyof T ? PathValue<T[K], R> : never
  : P extends keyof T ? T[P] : never;

interface User { name: string; addr: { city: string; geo: { lat: number } } }

type UP = Paths<User>; // "name" | "addr" | "addr.city" | "addr.geo" | "addr.geo.lat"
type City = PathValue<User, 'addr.city'>; // string
type Lat = PathValue<User, 'addr.geo.lat'>; // number

// Type-safe get
function get<T, P extends Paths<T>>(o: T, p: P): PathValue<T, P> {
  return p.split('.').reduce((x: any, k) => x?.[k], o);
}

const user: User = { name: 'A', addr: { city: 'NYC', geo: { lat: 40 } } };
const city = get(user, 'addr.city');    // string
const lat = get(user, 'addr.geo.lat');  // number

// Real-world: React Hook Form tracks visited types to prevent infinite recursion
type PathImpl<T, Seen = never> = T extends object
  ? T extends Seen ? never
  : { [K in keyof T & string]: K | `${K}.${PathImpl<T[K], Seen | T>}` }[keyof T & string]
  : never;

Resources

Practice

Hints

  • Use recursive template literal types to generate all valid dot-notation paths.
  • Split the path string at "." using template literal infer to traverse the type.