You need to enable JavaScript to run this app. TypeScript继承父类时如何将属性重写为get/set访问器?
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript继承父类时如何将属性重写为get/set访问器?

报错原因

Property 'value' in type 'B' is not assignable to the same property in base type 'A'.

这个错误是 TypeScript 有意设计的校验规则:不允许将基类中定义的实例字段重写为访问器属性。因为实例字段是直接挂载在类实例对象上的,优先级高于原型链上的访问器属性,直接重写会导致运行时逻辑和类型声明不符,因此 TS 直接禁止了这种写法,和泛型参数是否指定无关。


解决方案

方案1:可修改父类A的定义时

把父类的value从实例字段调整为访问器,后续子类即可正常重写:

class A<T> {
  protected _value: T;
  get value(): T {
    return this._value;
  }
  set value(newValue: T) {
    this._value = newValue;
  }
}

class B extends A<string> {
  private pValue: string = '';
  // 加override关键字显式标注重写,更符合TS规范
  override get value(): string {
    return this.pValue;
  }
  override set value(newValue: string) {
    if (newValue !== this.pValue) {
      this.pValue = newValue;
    }
  }
}

方案2:不可修改父类A的定义时

用TS工具类型Omit在继承时剔除父类的value属性声明,同时在构造函数中删除父类挂载到实例上的value字段,避免运行时优先级覆盖:

class B extends Omit<A<string>, 'value'> {
  private pValue: string = '';

  constructor() {
    super();
    // 删除父类挂在实例上的value字段,让访问器正常生效
    delete (this as any).value;
  }

  get value(): string {
    return this.pValue;
  }
  set value(newValue: string) {
    if (newValue !== this.pValue) {
      this.pValue = newValue;
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 17:57:00