Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call an overridden method in base class constructor in typescript

When I'm calling an overridden method from the base class constructor, I cannot get a value of a sub class property correctly.

Example:

class A {     constructor()     {         this.MyvirtualMethod();     }      protected MyvirtualMethod(): void     {      } }  class B extends A {     private testString: string = "Test String";      public MyvirtualMethod(): void     {         alert(this.testString); // This becomes undefined     } } 

I would like to know how to correctly override functions in typescript.

like image 805
Sency Avatar asked Jun 13 '15 14:06

Sency


People also ask

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.

How do you call a base class overridden method?

Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword. Overriding and constructor : We can not override constructor as parent and child class can never have constructor with same name(Constructor name must always be same as Class name).

Does TypeScript support function overriding?

TypeScript override method can be used to implement overriding in TypeScript Method overriding in TypeScript is a language feature that allows a derived class to provide a specific implementation of a method that is already provided by one of its or base classes.

What is method 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.


1 Answers

The key is calling the parent's method using super.methodName();

class A {     // A protected method     protected doStuff()     {         alert("Called from A");     }      // Expose the protected method as a public function     public callDoStuff()     {         this.doStuff();     } }  class B extends A {      // Override the protected method     protected doStuff()     {         // If we want we can still explicitly call the initial method         super.doStuff();         alert("Called from B");     } }  var a = new A(); a.callDoStuff(); // Will only alert "Called from A"  var b = new B() b.callDoStuff(); // Will alert "Called from A" then "Called from B" 

Try it here

like image 96
Flavien Volken Avatar answered Sep 21 '22 13:09

Flavien Volken