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

TypeScript抽象类中如何让方法返回子类类型并解决this泛型赋值报错

解决方案

方案1:使用 TypeScript 内置多态 this 类型(推荐)

这是最符合 TypeScript 设计规范的解法,不需要手动声明泛型参数,完全规避类型不匹配的报错:

abstract class Foo {
  // child类型自动匹配当前子类类型
  child: this
  // 返回this时自动匹配当前子类类型
  foo(): this {
    return this
  }
  getChild(): this {
    return this.child
  }
  // 你之前抽离的20多个公共方法都可以直接放到基类里
  fooFn(child: this): this {
    return child
  }
}

class Bar extends Foo {
  bar = true
}

const foo = new Bar()
// 所有方法返回值都自动识别为Bar类型,可正常调用bar属性
foo.foo().bar
foo.getChild().bar
foo.fooFn(foo.child).bar

该方案的原理是 TypeScript 内置的多态 this 类型会和当前实例的实际类型绑定,继承时自动向下匹配子类类型,不存在泛型方案里「泛型参数可能和实际子类不匹配」的问题,无需任何类型断言。

方案2:基类统一封装类型断言

如果你的业务逻辑确实需要保留泛型参数 C(比如需要在类外部引用该泛型、存在其他复杂类型约束),可以在基层做一次统一断言,后续所有逻辑直接调用封装后的属性即可,不用重复写断言:

abstract class Foo<C extends Foo<C>> {
  // 仅做一次类型断言,全基类通用
  protected get self(): C {
    return this as unknown as C
  }

  child: C
  foo(): C {
    // 直接用self,无需重复断言
    return this.self
  }

  getChild(): C {
    return this.child
  }
}

class Bar extends Foo<Bar> {
  bar = true
}

const foo = new Bar()
foo.foo().bar
foo.getChild().bar

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:48:02