如何为TypeScript泛型属性指定参数并获取应用后的类型?
TypeScript泛型方法的类型层面实例化实现
首先明确:TypeScript本身不支持Foo['foo']<string>这种直接对类型提取后的泛型函数传参的语法,但可以通过条件类型+infer关键字实现等价的类型操作,得到(arg: string) => string的类型。
具体实现方案
先回顾原类型定义:
type Foo = { foo<T>(arg: T): T }
方案1:针对性工具类型
写一个专门处理Foo['foo']这类单参数泛型方法的工具类型:
// 工具类型:给指定对象的指定方法应用泛型参数 type ApplyMethodGeneric<Obj, MethodName extends keyof Obj, GenericArg> = Obj[MethodName] extends <U>(arg: U) => U ? (arg: GenericArg) => GenericArg : never; // 使用示例 type Bar = ApplyMethodGeneric<Foo, 'foo', string>; // Bar的类型为:(arg: string) => string
方案2:通用泛型函数工具类型
如果需要适配更多类型的泛型函数,可以写更通用的工具:
// 工具类型:给泛型函数应用指定的泛型参数 type ApplyGeneric<GenericFn extends <U>(...args: any[]) => any, TargetArg> = GenericFn extends <U>(arg: U) => infer ReturnType ? (arg: TargetArg) => (ReturnType extends U ? TargetArg : ReturnType) : never; // 使用示例 type FooFooMethod = Foo['foo']; type Bar = ApplyGeneric<FooFooMethod, string>; // Bar的类型同样为:(arg: string) => string
原理说明
TypeScript的条件类型结合infer可以提取泛型函数的参数和返回值结构,我们通过判断泛型函数的形状,将原泛型参数U替换为目标类型string,从而得到实例化后的函数类型。
内容的提问来源于stack exchange,提问作者TrevTheDev
相关产品推荐
相关产品推荐

