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

如何将泛型参数约束为实现特定接口的类/构造函数?

无需抽象存根类的实现方案

完全可以不用定义抽象存根类,直接通过构造函数签名类型来约束泛型参数,要求它是能生成实现指定接口实例的构造函数。

具体实现代码

interface Interface {
    get FooVal(): any;
}

// 直接约束泛型为:能生成Interface实例的构造函数
function Foo<T extends new (...args: any[]) => Interface>(bar: T) { }

class UserClass implements Interface {
    get FooVal() { return null; }
}

Foo(UserClass); // 无错误/警告,符合预期

原理说明

  • new (...args: any[]) => Interface 是TypeScript中的构造函数类型签名,表示:这是一个可以接受任意参数(...args: any[])、并且返回Interface类型实例的构造函数。
  • 通过T extends new (...args: any[]) => Interface,我们直接把泛型T约束为所有满足“实例实现Interface”的类的构造函数类型,完全替代了原方案中通过typeof StubClass获取构造函数类型的方式。

扩展:更精准的参数约束

如果需要限制构造函数的参数类型,可以把...args: any[]替换为具体的参数列表。比如要求构造函数接受一个string参数:

function Foo<T extends new (name: string) => Interface>(bar: T) { }

class UserClass implements Interface {
    constructor(name: string) {}
    get FooVal() { return null; }
}

Foo(UserClass); // 正常通过

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:23:20