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
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