非递归实现通过字符串数组遍历对象的TypeScript类型
非递归TypeScript类型实现对象路径遍历需求
需求
需要构建非递归的TypeScript类型,用于通过字符串数组遍历对象结构,路径中需支持:
- 对象的键名
- 数组索引(可以是数字或针对数组元素的断言函数
PredicateFunction)
现有尝试及问题
我尝试了如下实现,但该方案在首个数组索引后失效,推测TypeScript无法推断后续键值:
export type StatePath< State, Key1 extends keyof State, Type1 extends (State[Key1] extends (infer Type1)[] ? Type1 : State[Key1]), ArrayIndex2 extends (State[Key1] extends (infer Type1)[] ? [(number | PredicateFunction<Type1>)] : []), Key2 extends keyof Type1, Type2 extends (Type1[Key2] extends (infer Type2)[] ? Type2 : Type1[Key2]), ArrayIndex3 extends (Type1[Key2] extends (infer Type2)[] ? [(number | PredicateFunction<Type2>)] : []), Key3 extends keyof Type2, Type3 extends (Type2[Key3] extends (infer Type3)[] ? Type3 : Type2[Key3]), ... > = | [Key1] | [Key1, ...ArrayIndex2] | [Key1, ...ArrayIndex2, Key2] | [Key1, ...ArrayIndex2, Key2, ...ArrayIndex3] | [Key1, ...ArrayIndex2, Key2, ...ArrayIndex3, Key3] ... export interface TestState { test1: { test2: { test3: string[]; }; test4: { test5: string }; } } const test: StatePath<TestState> = ["test1", "test2", "test3"];
现有实现只能手动扩展有限层级,且后续键的类型推断完全失效,无法正确识别合法路径(比如示例中的["test1", "test2", "test3"]),恳请提供解决思路!
内容的提问来源于stack exchange,提问作者Stefan Holzapfel
相关产品推荐
相关产品推荐

