The super keyword
When using inheritance, both a base class and a derived class may have the same function name. This is most often seen with class constructors. If a base class has a defined constructor, then the derived class may need to call through to the base class constructor and pass through some arguments. This technique is called constructor overriding. In other words, the constructor of a derived class overrides, or supersedes, the constructor of the base class. TypeScript includes the super keyword to enable calling a base class's function with the same name. Consider the following classes:
class BaseClassWithConstructor { private id: number; constructor(_id: number) { this.id = _id; } } class DerivedClassWithConstructor extends BaseClassWithConstructor { private name: string; constructor(_id: number, _name: string) { super(_id); this.name = _name; } }
Here, we define a class named BaseClassWithConstructor that holds a private id property. This class has a constructor function that requires an _id argument. Our second class, named DerivedClassWithConstructor, extends (or inherits from) the BaseClassWithConstructor class. The constructor of DerivedClassWithConstructor takes an _id argument and a _name argument. However, it needs to pass the incoming _id argument through to the base class. This is where the super call comes in. The super keyword calls the function in the base class that has the same name as the function in the derived class. The first line of the constructor function for DerivedClassWithConstructor shows the call using the super keyword, passing the id argument it received through to the base class constructor.