'… incorrectly extends base class static side' error when overriding static field in derived class

大城市里の小女人 提交于 2020-01-23 07:01:28

问题


Overriding static field in derived class causes

error TS2417: Build:Class static side 'typeof TDerived' incorrectly extends base class static side 'typeof TBase'.

Is this a legit error case?

class TBase
{
  private static s_field = 'something';

  public constructor() {}
}

class TDerived extends TBase
{
  private static s_field = 'something else'; // commenting this line fixes error

  public constructor()
  {
    super();
  }
}

How should i deal with static fields then? The only workaround right now would be to prepend class name to every static field name which is an exceptionally ugly solution.

private static TBase_s_field = 'something';
...
private static TDerived_s_field = 'something else';

ps using typescript 2.0.3


回答1:


You cannot redeclare a private field in a derived class. Use protected if you intend for derived classes to be able to redeclare or access the field.

This is enforced because static methods are also available in the derived class. For example, this code does something unexpected (if we ignore the compile error):

class Base {
    private static foo = 'base';

    static printName() {
        // Should always print 'base' because no one
        // else has access to change 'foo'
        console.log(this.foo);
    }
}

class Derived extends Base {
    private static foo = 'derived';
}
// Will actually print 'derived'
Derived.printName();


来源:https://stackoverflow.com/questions/39799195/incorrectly-extends-base-class-static-side-error-when-overriding-static-fi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!