The super Function and Function Overriding
Learn how to use the super keyword to call base class constructors and method overrides.
We'll cover the following...
The super
function
When using inheritance, it is quite common for a base class and a derived class to implement the same method. This is seen most often with class constructors. If a derived class has a constructor, then this constructor must call the base class constructor using the super
keyword, or TypeScript will generate an error as follows:
// Class definition for BaseClassWithCtorclass BaseClassWithCtor {// private property to store the idprivate id: number;// constructor to initialize the idconstructor(id: number) {this.id = id;}}// Class definition for DerivedClassWithCtor that extends BaseClassWithCtorclass DerivedClassWithCtorextends BaseClassWithCtor {// private property to store the nameprivate name: string;// constructor to initialize the id and nameconstructor(id: number, name: string) {// calling the super constructor to initialize the idsuper(id);this.name = name;}}
Using the super keyword
-
We define a class named
BaseClassWithCtor
from lines 2–10 that has a single property namedid
of typenumber
and also defines aconstructor
function that initializes thisid
property. -
We then define a class named
DerivedClassWithCtor
from ...