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

TypeScript子类使用抽象类方法的ReturnType时报错如何解决?

问题原因

报错的核心是你在公共方法的返回类型里使用了typeof this.getValue,这里的this属于类实例的内部上下文,TypeScript 不允许公共方法的返回类型依赖外部无法访问的this上下文,因此触发了类型报错。

解决方案

将返回类型的引用源从实例this改为直接从父类索引对应的方法类型即可,无需依赖实例上下文,以下是两种可行改法:

改法1:适配父类类型变动的通用写法

如果你需要后续父类修改getValue返回类型时,子类的返回类型自动同步,用这种写法最稳妥:

abstract class Parent<A>{
    private _value:A
    constructor (value:A){
        this._value=value
    }

    protected getValue():A {
        return this._value
    }

}

class ChildString extends Parent<string>{
    constructor(value:string){
        super(value)
    }

    public stringValue(): ReturnType<Parent<string>['getValue']> {
        return this.getValue()
    }
}

Parent<string>['getValue']是直接从父类实例类型上索引到getValue方法的类型,完全不依赖当前实例的this,不会触发访问权限类的类型报错。

改法2:简单场景直接声明明确类型

你的当前场景下getValue的返回类型就是string,直接写明确的返回类型也可以,代码可读性更高:

public stringValue(): string {
    return this.getValue()
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:21:00