如何在TypeScript中实现递归式对象路径FieldPath类型约束?
TypeScript实现带类型约束的FieldPath类型
可以实现这样的FieldPath类型,它能基于对象结构提供严格的路径类型校验,完全满足你列出的所有约束场景。
示例对象
const obj = { name: 'Test', city: { name: 'London' }, tags: [ { name: 'tag1' }, { name: 'tag2' } ] }
FieldPath类型实现
type FieldPath<T> = T extends Array<infer U> ? [number, ...FieldPath<U>] | [number] : T extends object ? { [K in keyof T]: [K] | [K, ...FieldPath<T[K]>]; }[keyof T] : [];
类型校验验证
以下是对应需求的测试案例,非法路径会触发TypeScript类型错误:
// 合法的对象属性访问 const path1: FieldPath<typeof obj> = ['name'] // 非法属性,报错:Type '"nope"' is not assignable to type ... const path2: FieldPath<typeof obj> = ['nope'] // 合法的嵌套对象属性访问 const path3: FieldPath<typeof obj> = ['city', 'name'] // 嵌套对象的非法属性,报错 const path4: FieldPath<typeof obj> = ['city', 'nope'] // 合法的数组索引访问 const path5: FieldPath<typeof obj> = ['tags', 1] // 数组的非法属性,报错 const path6: FieldPath<typeof obj> = ['tags', 'nope'] // 合法的递归路径访问 const path7: FieldPath<typeof obj> = ['tags', 1, 'name'] // 递归路径的非法属性,报错 const path8: FieldPath<typeof obj> = ['tags', 1, 'nope']
实现说明
- 针对数组类型:允许单个数字索引,同时支持在索引后追加数组元素类型的递归路径
- 针对对象类型:遍历对象所有键,每个键既可以作为单元素路径,也可以作为路径开头,后面追加对应属性值类型的递归路径
- 针对非对象/非数组类型:返回空数组终止递归
内容的提问来源于stack exchange,提问作者ciscoheat
相关产品推荐
相关产品推荐

