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

TypeScript中扩展方法里new this返回基类,如何让其返回子类类型?

解决TypeScript中静态方法返回子类实例类型的问题

你只需要给Model的load静态方法显式指定返回类型,就能让子类调用load时返回对应子类的实例类型,这里提供两种可行方案:

方案一:利用InstanceType和typeof this

class Model {
    constructor() { }
    static load(): InstanceType<typeof this> {
        return new this() as InstanceType<typeof this>;
    }
}

class User extends Model { }

let user = User.load(); 
// 现在user的类型为User,符合预期

原理

  • 静态方法里的this指向调用该方法的类本身(比如User.load()里的this就是User类)
  • typeof this获取当前类的构造函数类型,InstanceType<typeof this>则代表该构造函数生成的实例类型
  • 加as InstanceType<typeof this>是因为TypeScript暂时无法自动推断new this()的具体子类类型,需要手动做类型断言

方案二:用泛型构造函数约束

class Model {
    constructor() { }
    static load<T extends Model>(this: new () => T): T {
        return new this();
    }
}

class User extends Model { }

let user = User.load(); 
// user类型为User

原理

  • 通过给静态方法添加this参数(仅用于类型推断),约束当前类是一个能创建T实例的构造函数
  • 这样TypeScript就能直接推断出返回类型为子类T,无需额外类型断言

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:31:00