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

如何从TypeScript类中提取泛型类型?

解决TypeScript类泛型类型提取失败的问题

问题原因

你遇到的问题本质是:当泛型参数FUNCTION在BaseComponent类内部没有被实际使用时,TypeScript编译器会将其替换为泛型约束的上限类型(...args: any) => any,导致ExtractFunction无法提取到子类传入的具体泛型类型。

解决方案

要让TypeScript保留泛型的具体类型,必须让泛型参数在类的结构中被引用(比如作为类的属性、方法类型、方法参数/返回值等)。下面是两种可行的修改方式:

方式1:添加抽象属性/方法绑定泛型类型

修改BaseComponent,添加一个类型为FUNCTION的抽象成员,强制子类实现时带入具体类型:

type ExtractFunction<T> = T extends BaseComponent<infer U> ? U : never;

abstract class BaseComponent<FUNCTION extends (...args: any) => any> {
  // 定义抽象属性,类型绑定到泛型FUNCTION
  abstract invoke: FUNCTION;
}

// 子类继承时必须传入具体的函数类型并实现invoke属性
class MyButton extends BaseComponent<(text: string) => void> {
  invoke(text: string): void {
    console.log(text);
  }
}

// 现在能正确提取到 (text: string) => void
type ButtonFunc = ExtractFunction<MyButton>;

方式2:通过构造函数参数绑定泛型

如果不想添加类成员,也可以在构造函数中使用泛型参数:

type ExtractFunction<T> = T extends BaseComponent<infer U> ? U : never;

abstract class BaseComponent<FUNCTION extends (...args: any) => any> {
  constructor(protected func: FUNCTION) {}
}

class MyInput extends BaseComponent<(value: number) => boolean> {
  constructor(func: (value: number) => boolean) {
    super(func);
  }
}

// 正确提取到 (value: number) => boolean
type InputFunc = ExtractFunction<MyInput>;

原理说明

TypeScript的泛型擦除机制会忽略未被使用的泛型参数,将其替换为约束的上限类型。只有当泛型参数出现在类的公共API(属性、方法、构造函数参数等)中时,编译器才会保留具体的泛型类型信息,让infer能够正确提取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 11:05:31