Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i avoid a function to be overridden in the Child Class in TypeScript ?

Tags:

typescript

According to the example given below , i don't want Class B or any other classes which extends A be able to override funcA.

Can this be done in TypeScript ? If yes then, How ?

export class A {
    protected funcA(){

    }
}

export class B extends A {
    //Not able to override funcA()

}
like image 842
Aakash Uniyal Avatar asked Feb 27 '18 05:02

Aakash Uniyal


People also ask

Can we override function type 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.

What is function overriding in TypeScript?

Method Overriding is the process in which a method belonging to the base (or parent) class is overridden by the same method (same method and signature) of the derived (child) class. In this process, a child (derived) class method may or may not use the logic defined in the parent (base) class method.

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.

What is protected in TypeScript?

protected implies that the method or property is accessible only internally within the class or any class that extends it but not externally. Finally, readonly will cause the TypeScript compiler to throw an error if the value of the property is changed after its initial assignment in the class constructor.


1 Answers

Update for TS 4.3 and above

Typescript 4.3 adds a new compiler option called noImplicitOverride in this PR. This makes it an error to mistakenly override class methods without the override keyword

class Base{
    method() {}
    method2 () {}
} 

class Derived extends Base {
    method() {} // err 
    override method2() {} // ok
} 

(playground does not support the option yet, but works in vs code)

Original answer pre 4.3

There is no way to prevent a public/protected member from beeing overriden. The compiler will trigger an error if you to this with private members only. A feature for this has been proposed but not implemented

like image 70
Titian Cernicova-Dragomir Avatar answered Sep 20 '22 22:09

Titian Cernicova-Dragomir