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?
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?
2 Answers
Reset to default 16Since 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) {
}
It's all very strange, but if you really need to, try this:
class Foo {
private go() {
}
}
class Bar extends Foo {
constructor() {
super();
this["go"] = this.foo;
}
private foo() {
}
}
A
into an interface, and move the existingA.method
into a new abstract class that implementsA
? – earldouglas Commented Feb 16, 2018 at 15:27What can I do to have two private methods that are named the same?
- When extending one class from another you cannot have two private methods named the same as explained in this - Possible duplicate of typescript derived class cannot have the same variable name? – Nope Commented Feb 16, 2018 at 15:32