Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Overloading private method

Hello I would like to achieve this scenario:

class A implements InterfaceForA
{
    a():void
    {
        this.b();
    }
}

Class B extends A
{
    private b():void
    {
        console.log('Hi');
    }
}

But it throws:

error TS2339: Property 'b' does not exist on type 'A'.

So I updated my class and now it throws:

error TS2415: Class 'B' incorrectly extends base class 'A'. Types have separate declarations of a private property 'b'.

With code:

class A implements InterfaceForA
{
    a():void
    {
        this.b();
    }

    private b():void
    {
        console.log('Hello');
    }
}

Class B extends A
{
    private b():void
    {
        console.log('Hi');
    }
}

In C++, I would set in class A method b() as virtual private, and problem would be solved. In JS it wouldn't be problem at all. How to do it in TypeScript?

like image 699
user1440445 Avatar asked Jun 22 '15 06:06

user1440445


People also ask

Can we override private method in TypeScript?

Using protected is the correct way to solve this! But if you have no access to the parent class (e.g. because it is within a library) you also could overwrite private class member-function in the constructor.

Does TypeScript support function overriding?

TypeScript - Function OverloadingTypeScript provides the concept of function overloading. You can have multiple functions with the same name but different parameter types and return type. However, the number of parameters should be the same.

Can we override private method in Javascript?

You can't this way.

How do you override a base class method in TypeScript?

To override a class method in TypeScript, extend from the parent class and define a method with the same name. Note that the types of the parameters and the return type of the method have to be compatible with the parent's implementation. Copied! class Parent { doMath(a: number, b: number): number { console.


1 Answers

In C++ you would actually set it as protected. Private members are private.

Typescript >= 1.3 supports protected qualifier.

See: What is the equivalent of protected in TypeScript?

like image 93
Andrei Tătar Avatar answered Oct 09 '22 04:10

Andrei Tătar