Basics

Challenges

Classes

Cookies

Debugging

Events

External Files

Flow Control

Forms

Functions

Html Elements

Installation

Interfaces

Keywords

Modules

Namespaces

Operators

Reference Files

String

Types

TypeScript - super

If you have a class (ex: Cat) which extends another class (abstract or not, ex: Animal), and your derived class (Cat) has a constructor, then you must use the super function keyword.

Each derived class (Cat) that contains a constructor function must call super() which will execute the constructor of the base class...even if the base class has an empty/no constructor. Before we ever access a property on this in a constructor body, we have to call super(). This is an important rule that TypeScript will enforce.

Observe the code below.

  • Animal requires an argument of name when instantiated
  • Cat requires the Animal argument as well as it's own - ColorOfFur
  • Because Cat extends Animal, you must provide both arguments
  • Because Cat has a Constructor, yo must use the super keyword. This will invoke the Animal constructor....even if it was empty(missing)
  • You can completely remove the Animal constructor and super is still required in Cat because Cat has it's own Constructor.

class Animal
{
    Name: string = "";

    constructor(name: string)
    {
        this.Name = name;
    }
}

class Cat extends Animal
{
    ColorOfFur: string = "";

constructor(name: string, furColor: string)
    {
        super(name);
        this.ColorOfFur = furColor;
    }

    Greeting = () : string => `${this.Name} says meow and his color is ${this.ColorOfFur}.`;
}

window.onload = function ()
{
    let cat = new Cat("Spot", "Orange");
    let superDemo = <HTMLElement>document.getElementById("super-demo");
    superDemo.innerHTML = cat.Greeting();
};