You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 09:22:28