Recursive Key Path Types For Dot Notation

A recursive mapped type collects every leaf dot path of a nested config, and a readPath helper typed over those paths makes invalid keys a compile-time error.

TypescriptConfig Management

Code

typescriptsnippet
56 lines
// A recursive type collects every dot path of an object: only leaves are readable,
// a misspelled key or an intermediate stop becomes a compile error
interface DeployConfig {
  region: string;
  replicas: number;
  resources: { cpu: string; memoryMb: number };
}

type Paths<T, P extends string = ''> = T extends object
  ? {
      [K in keyof T & string]: Paths<T[K], `${P}${P extends '' ? '' : '.'}${K}`>;
    }[keyof T & string]
  : P;

type ConfigPath = Paths<DeployConfig>;
const valid: ConfigPath = 'resources.memoryMb';
console.log('valid path:', valid);

type PathValue<T, P extends string> = P extends `${infer Head}.${infer Rest}`
  ? Head extends keyof T
    ? PathValue<T[Head], Rest>
    : never
  : P extends keyof T
    ? T[P]
    : never;

function readPath<T extends object, P extends Paths<T> & string>(
  config: T,
  path: P,
): PathValue<T, P> {
  let cursor: unknown = config;
  for (const segment of path.split('.')) {
    cursor = (cursor as Record<string, unknown>)[segment];
  }
  return cursor as PathValue<T, P>;
}

const config: DeployConfig = {
  region: 'cn-east-1',
  replicas: 3,
  resources: { cpu: '500m', memoryMb: 512 },
};

const region: string = readPath(config, 'region');
const memoryMb: number = readPath(config, 'resources.memoryMb');
console.log(region, 'memoryMb =', memoryMb);

type ExpectEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2
  ? true
  : never;
const locked: ExpectEqual<
  ConfigPath,
  'region' | 'replicas' | 'resources.cpu' | 'resources.memoryMb'
> = true;
console.log('path union locked:', locked);
// readPath(config, 'resources.gpu') - compile error: the path does not exist

Output

Captured from a sandboxed run of this snippet in the build pipeline.

valid path: resources.memoryMb
cn-east-1 memoryMb = 512
path union locked: true

How it works

Repetition is confined to for (const segment of path.split('.')) — the rest of the file is straight-line.

Applying it

Look for the valid path:, path union locked: prefixes when the file runs; they tie each line to its step.

Statements that matter

type PathValue<T, P extends string> = P extends `${infer Head}.${infer Rest}`
  ? Head extends keyof T
    ? PathValue<T[Head], Rest>
    : never
  : P extends keyof T
    ? T[P]
    : never;
[K in keyof T & string]: Paths<T[K], `${P}${P extends '' ? '' : '.'}${K}`>;
return cursor as PathValue<T, P>;

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit.