Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class 'B' incorrectly extends base class 'A' (two private methods named the same)

I am getting the error

Class 'B' incorrectly extends base class 'A'.
Types have separate declarations of a private property 'method'.

abstract class A {
  private method() {}
}

abstract class B extends A {
  private method() {}
}

When the method in class A is commented out, then the error goes away. What can I do to have two private methods that are named the same?

like image 536
Get Off My Lawn Avatar asked Sep 16 '25 09:09

Get Off My Lawn


1 Answers

Since Typescript sits on top of Javscript, and Javascript does not allow inherited classes to have different private implementations for a function (all functions will end up on the prototype of the class) it makes sense that Typescript would not allow you to do this.

If this were allowed you would be basically be overriding the private member method and since it is marked as private it was probably not intended for public consumption/overriding.

You could override the function if you declared it as public/protected

abstract class A {
    protected method() { }
}

abstract class B extends A {
    protected method() { }
}

Or if you really want to override a private method, you could do the following, although private methods are marked as private for a reason and it may be best to avoid this:

class B extends A {

}
(B.prototype as any)['method'] = function(this: B) {
}
like image 117
Titian Cernicova-Dragomir Avatar answered Sep 18 '25 00:09

Titian Cernicova-Dragomir