Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 892
dodo951 Avatar asked Sep 30 '16 19:09

dodo951


1 Answers

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();
like image 160
Ryan Cavanaugh Avatar answered Nov 15 '22 07:11

Ryan Cavanaugh