实现说明
这个文件只在 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