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

如何在类方法中实现多态,返回对应子类实例并解决类型报错

问题原因

TypeScript 默认将 this.constructor 推导为通用的 Function 类型,该类型没有定义构造调用签名,因此直接调用 new this.constructor() 会触发类型报错,这个问题只存在于类型校验阶段,运行时你的原始写法本身是可以正常工作的。

解决方案

只需要给 this.constructor 加上对应的类型断言,声明它是可以被构造、且返回实例类型为当前类实例的构造函数即可:

class Foo {
  makesAnother(): this {
    // 类型断言:指明constructor是无参构造函数,返回当前类的实例
    const Ctor = this.constructor as new () => this;
    return new Ctor();
  }
}

class Bar extends Foo {}
const bar = new Bar();
const newBar = bar.makesAnother();
// 运行时:newBar instanceof Bar 结果为 true
// 类型推导:newBar 的类型自动为 Bar,符合预期

扩展场景:构造函数带参数

如果你的类构造函数需要传入参数,可以调整断言的构造函数签名,支持参数透传:

interface Constructor<T> {
  new (...args: any[]): T;
}

class Foo {
  constructor(public name: string) {}

  makesAnother(newName: string): this {
    const Ctor = this.constructor as Constructor<this>;
    return new Ctor(newName);
  }
}

class Bar extends Foo {
  sayHi() {
    console.log(`Hi, I'm ${this.name}`);
  }
}

const bar = new Bar("old bar");
const newBar = bar.makesAnother("new bar");
newBar.sayHi(); // 正常执行,类型校验无报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:54:03