如何在TypeScript中实现嵌套对象同级属性类型自动推断?
实现自动推导类型的
test函数 要满足你提出的需求——让test函数自动推导method的参数类型,同时保留所有属性的具体类型而非any,可以通过TypeScript的泛型映射类型实现类型关联,以下是具体方案:
实现代码
// 定义嵌套对象的类型模板,用泛型关联property和method的类型 type NestedProp<P, K, A> = { property: () => P; anotherProperty: () => A; key: K; method: (data: P) => void; }; // 定义test函数,通过映射类型遍历外层对象的每个键,精准推导嵌套类型 function test<T extends Record<string, NestedProp<any, any, any>>>( obj: { [K in keyof T]: NestedProp<ReturnType<T[K]['property']>, T[K]['key'], ReturnType<T[K]['anotherProperty']>> } ) {} // 示例用法 function key({ productId }: { productId: number }) { return ['list', { productId }]; } test({ list: { property: () => 'string', anotherProperty: () => 1, // 类型保留为() => number,而非any key, // 类型保留为({ productId: number }) => string[] method: (data) => { // data自动推断为string类型,可直接调用string的方法 console.log(data.toUpperCase()); }, }, detail: { property: () => ({ id: 123 }), anotherProperty: () => true, // 类型保留为() => boolean key: ({ userId }: { userId: string }) => ['detail', { userId }], method: (data) => { // data自动推断为{ id: number }类型,可直接访问id属性 console.log(data.id); }, }, });
核心逻辑说明
- 用泛型
NestedProp<P, K, A>分别绑定property返回值、key、anotherProperty返回值的类型,确保每个属性的类型都被精准捕获。 - 通过映射类型
{ [K in keyof T]: ... }遍历外层对象的所有动态键,将每个嵌套对象的method参数类型与对应property的返回值类型做绑定,实现自动推导。 - 所有属性的具体类型都会被TypeScript完整保留,不会被降级为
any,类型检查和智能提示完全有效。
内容的提问来源于stack exchange,提问作者Tomas Lachmann
相关产品推荐
相关产品推荐

