提取深度嵌套对象、数组及对象数组的点表示法键(排除索引)
解决方案:提取TypeScript深层嵌套键(排除数组索引)
我们可以通过递归类型工具实现需求,直接跳过数组索引,提取数组元素的深层键,无需引入${number}或具体索引值。
核心类型实现
// 获取数组的元素类型,非数组则返回原类型 type ElementType<T> = T extends Array<infer U> ? U : T; // 递归提取深层键 type DeepKeys<T> = T extends object ? { [K in keyof T & string]: // 保留当前键,或拼接当前键与子类型的深层键 K | `${K}.${DeepKeys<ElementType<T[K]>>}` }[keyof T & string] : never;
测试代码
将上述类型应用到你的示例中:
type Pack = { name: string items: string[] } interface Params { name: string items: string[] pack: Pack packs: Pack[] nested1: { nested2: { nested3: string }[] } } type ParamKeys = DeepKeys<Params>; // 结果:'name' | 'items' | 'pack' | 'pack.name' | 'pack.items'| 'packs' | 'packs.name' | 'packs.items' | 'nested1' | 'nested1.nested2'| 'nested1.nested2.nested3'
退而求其次:固定索引0的实现
如果某些场景下无法直接跳过索引,可将数组索引固定为0,生成带0的路径:
type DeepKeysWithFixedIndex<T> = T extends Array<infer U> ? { [K in keyof T & string]: K | `${K}.0.${DeepKeysWithFixedIndex<U>}` }[keyof T & string] : T extends object ? { [K in keyof T & string]: K | `${K}.${DeepKeysWithFixedIndex<T[K]>}` }[keyof T & string] : never; // 测试 type ParamKeysWithIndex = DeepKeysWithFixedIndex<Params>; // 结果包含:'nested1.nested2.0.nested3' 等带0索引的路径
类型逻辑说明
- ElementType
: 判断输入类型是否为数组,若是则返回数组元素类型,否则返回原类型,实现跳过数组直接处理元素的逻辑。 - DeepKeys
: 遍历对象的所有字符串键,对每个键生成两种路径: - 键本身(如
packs) - 键与子类型深层键的拼接(如
packs.name,通过递归处理数组元素的类型实现无索引路径)
- 键本身(如
内容的提问来源于stack exchange,提问作者LittleFoxyFox
相关产品推荐
相关产品推荐

