如何将TypeScript接口映射为带重载get方法的交叉类型泛型S<A>
基于接口A自动生成服务S的重载get方法类型
我们可以通过映射类型结合你提供的UnionToIntersection工具类型,自动从接口A生成服务S的重载get方法类型,无需手动逐个定义重载分支。
完整实现代码
// 你提供的联合转交叉类型工具 type UnionToIntersection<U> = (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never; // 目标接口A interface A { a: string; b: number; c: boolean; } // 第一步:将A的每个键映射为对应的get函数类型(得到联合类型) type GetFunctionUnion<T> = { [K in keyof T]: (name: K) => T[K]; }[keyof T]; // 第二步:将联合类型转成交叉类型,得到重载函数的等价交叉类型 type GetFunction<T> = UnionToIntersection<GetFunctionUnion<T>>; // 最终生成服务S的类型 type S = { get: GetFunction<A>; };
验证使用
// 模拟服务实例 const service: S = { get: (name) => { // 这里可以写具体实现,类型会自动推导 if (name === 'a') return 'hello'; if (name === 'b') return 123; return true; } }; const c = service.get('c'); // 类型为boolean,符合预期 const a = service.get('a'); // 类型为string,符合预期 const b = service.get('b'); // 类型为number,符合预期
实现逻辑说明
GetFunctionUnion<T>:通过映射类型遍历T的所有键K,为每个键生成(name: K) => T[K]的函数类型,最后通过[keyof T]取出所有值的联合类型,得到类似((name: 'a') => string) | ((name: 'b') => number) | ((name: 'c') => boolean)的结果。GetFunction<T>:利用UnionToIntersection将上述联合类型转换为交叉类型,而TypeScript中,函数的交叉类型等价于重载函数的定义,这样就实现了自动生成重载的效果。S类型:将转换后的交叉类型赋值给get属性,就得到了和手动定义完全等价的服务类型。
内容的提问来源于stack exchange,提问作者malthe
相关产品推荐
相关产品推荐

