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

TypeScript获取类泛型方法返回类型遇解析错误求解决

问题描述

我无法获取类中泛型方法的类型,操作时出现解析错误。代码示例如下:

class MyClass<T extends string> {
  public myMethod<U extends string>(arg: U): [T, U] {}
}

type returnType = ReturnType<MyClass<'test'>['myMethod']['test']>;
// 报错:Unexpected token. Did you mean `{'>'}` or `&gt;`?(1382)

更新说明:为避免歧义已修改示例,原示例中的unknown类型仅为简化展示。返回类型同时依赖类泛型与方法泛型。

另外,尝试单独提取方法的方式也不可行:

type method = MyClass<'test'>['myMethod']

type returnType = ReturnType<method<'test'>>;

因为method并非泛型类型,将其设为泛型会触发完全相同的解析错误。

更新2:此问题并非返回类型相关,而是类型本身的问题,已提交相关Issue。


解决方法

方法1:用泛型工具类型推导返回类型

定义一个工具类型,通过条件类型结合infer来提取泛型方法的返回值:

class MyClass<T extends string> {
  public myMethod<U extends string>(arg: U): [T, U] {}
}

// 工具类型:接收实例化后的类方法和方法泛型参数,推导返回类型
type GenericMethodReturnType<Method extends (...args: any) => any, U> = 
  Method extends <U extends string>(arg: U) => infer R ? R : never;

// 获取目标返回类型
type returnType = GenericMethodReturnType<MyClass<'test'>['myMethod'], 'test'>;
// 最终 returnType 类型为 ['test', 'test']

方法2:通过条件类型匹配类结构

直接针对类的结构做条件判断,提取方法的返回类型:

// 工具类型:匹配类实例的myMethod方法,推导指定泛型参数下的返回类型
type GetMyMethodReturn<Instance, U> = 
  Instance extends { myMethod: <U extends string>(arg: U) => infer R } ? R : never;

type returnType = GetMyMethodReturn<MyClass<'test'>, 'test'>;

方法3:TS 4.7+ 简化写法

如果使用TypeScript 4.7及以上版本,语法支持更简洁的泛型参数推导:

type ExtractMethodReturn<Instance, U> = 
  Instance['myMethod'] extends <U extends string>(arg: U) => infer R ? R : never;

type returnType = ExtractMethodReturn<MyClass<'test'>, 'test'>;

这些方法的核心都是绕开TypeScript对“直接调用泛型方法类型”的语法限制,通过条件类型间接推导泛型参数对应的返回类型。


内容的提问来源于stack exchange,提问作者Maciej Kravchyk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 03:05:21