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

如何定义支持泛型指定继承类的TypeScript Class类型?

正确定义泛型Class类型的方案

你需要给泛型Class<T>设置默认类型参数,并让构造函数的返回类型指向T,这样既能在指定类型时限制构造函数必须生成T或其子类的实例,也能在不指定类型时兼容任意类构造函数。

正确的Class泛型定义

export type Class<T = any> = { new(...args: any[]): T; };

完整代码示例

export type Class<T = any> = { new(...args: any[]): T; };

class Document {
  id: string;
}

class Person extends Document {
  name: string;
}

class Foo {
  bar: string;
}

export class Orm {
  // 只接受继承自Document的类构造函数
  registerDocument(model: Class<Document>) {
  }

  // 接受任意类构造函数
  foo(acceptAnyClass: Class) {
  }
}

const orm = new Orm()
orm.registerDocument(Person) // 合法:Person继承自Document
orm.foo(Foo) // 合法:Foo是任意类
// orm.registerDocument(Foo) // 报错:Foo未继承Document,符合预期

说明

  • 给泛型T设置默认值any,当不写Class<>的类型参数时,就等价于Class<any>,即接受任意类构造函数。
  • 构造函数的返回类型设为T,意味着当你指定Class<Document>时,传入的构造函数必须能生成Document或其子类的实例,TypeScript会自动校验类的继承关系。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 01:50:21