← 中文资源

简体中文版本

递归键路径类型约束点号取值

用递归映射类型收集嵌套配置对象的全部叶子点路径,readPath 只接受这些合法路径:键拼错或取到中间层都会变成编译错误,路径 union 被类型断言锁死。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

这个文件只在 for (const segment of path.split('.')) 里循环。

使用要点

  • 直接运行文件,输出会带上标签,比如 valid path:、path union locked:——输出的每一行都能指回产生它的那次调用。

常见问题

依赖情况复杂吗?

一点也不复杂:零依赖,没有要锁版本或审计的东西。

核心语句

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>;

代码示例

// 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