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()
}
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With