Search⌘ K
AI Features

The super Function and Function Overriding

Explore how the super function operates in TypeScript inheritance, enabling derived classes to call base class constructors and override methods. Understand function overriding mechanics, including calling base methods using super, to effectively manage shared and customized behaviors between base and derived classes.

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:

TypeScript 4.9.5
// Class definition for BaseClassWithCtor
class BaseClassWithCtor {
// private property to store the id
private id: number;
// constructor to initialize the id
constructor(id: number) {
this.id = id;
}
}
// Class definition for DerivedClassWithCtor that extends BaseClassWithCtor
class DerivedClassWithCtor
extends BaseClassWithCtor {
// private property to store the name
private name: string;
// constructor to initialize the id and name
constructor(id: number, name: string) {
// calling the super constructor to initialize the id
super(id);
this.name = name;
}
}
Using the super keyword
  • We define a class named BaseClassWithCtor from lines 2–10 that has a single property named id of type number and also defines a constructor function that initializes this id property.

  • We then define a class named DerivedClassWithCtor from ...