TypeScript技术问询:如何从泛型中获取方法的参数类型?
从泛型中获取方法的参数类型
当然可以实现这个需求,核心是正确关联Keys的键与泛型T中的方法名,再借助TypeScript内置的Parameters工具类型提取参数类型。
修正并实现你的类型定义
你的MethodNames<T>当前是让Keys的每个键映射为T的所有键类型,这不符合实际需求。我们需要让Keys的每个键对应T中的特定方法名,调整后实现如下:
- 定义方法映射接口(
Keys的每个键作为别名,对应T中的方法名):
interface Keys { create: any; // any仅作为占位,实际对应T中的方法名,比如T有create方法时可写'create' // 可添加更多方法别名... }
- 约束
Keys每个键对应的T方法名:
type MethodNames<T> = { [P in keyof Keys]: keyof T; };
- 提取对应方法的参数类型:
type MethodParams<T, M extends MethodNames<T>> = { [P in keyof Keys]: Parameters<T[M[P]] extends (...args: any[]) => any ? T[M[P]] : never>; };
实际使用示例
假设我们有一个包含业务方法的类型:
type UserService = { create: (name: string, age: number) => void; update: (id: string, data: { name?: string }) => void; }; // 定义具体的方法别名与实际方法名的映射 type UserMethodNames = { create: 'create'; update: 'update'; }; // 获取参数类型集合 type UserMethodParams = MethodParams<UserService, UserMethodNames>; // UserMethodParams最终类型为: // { // create: [string, number]; // update: [string, { name?: string | undefined }]; // }
简化场景(别名与方法名一致)
如果Keys的键名和T中的方法名完全一致,可直接省略MethodNames,简化写法:
interface Keys { create: any; update: any; } type MethodParams<T> = { [P in keyof Keys]: Parameters<T[P] extends (...args: any[]) => any ? T[P] : never>; };
关键说明
Parameters<F>是TypeScript内置工具类型,专门用于提取函数类型F的参数列表类型。- 加入条件判断
T[M[P]] extends (...args: any[]) => any ? T[M[P]] : never,是为了避免T中对应属性非函数类型时出现类型错误。
内容的提问来源于stack exchange,提问作者Seth
相关产品推荐
相关产品推荐

