×
☰ See All Chapters

TypeScript Inheritance

Classes in TypeScript (like other languages) support single inheritance using extends keyword. Multiple inheritances are not supported, while a TypeScript class can have multiple subclasses, it can only have one immediate superclass. All the members of super class will be inherited into subclass (except constructor and private members) and can be accessed directly in subclass.

If you have a constructor in your parent class then you must call the parent constructor from your sub class constructor as the first statement.

Syntax to create subclass

class SubclassName extends SuperclassName  {  

          //Members of subclass  

}

TypeScript Inheritance Example

class Box {

    length: number;

    width: number;

    height: number;

    constructor( length: number,  width: number,  height: number) {

        this.height = height;

        this.length = length;

        this.width = width;

    }

    volume() : number {

      return this.length*this.width*this.height;

    }

}

 

class BoxWeight extends Box {

    length: number;

    width: number;

    height: number;

    depth: number;

    constructor( length: number,  width: number,  height: number, depth: number) {

        super(length, width, height);

        this.depth = this.depth;

    }

    volume() : number {

      return super.volume()*this.depth;

    }

}

this and super

Inside a class, the instance of same class can be obtained using the “this” keyword.

Inside a class, the instance of its super class can be obtained using the “super” keyword. Also super is used to invoke superclass constructor from inside subclass constructor.

TypeScript Polymorphism

In object-oriented programming, polymorphism refers to the ability to refer to a derived class by the type of a parent class. For example, the preceding example explained how a derived class can be created with the following code:

var boxWeightObj : BoxWeight = new BoxWeight(10, 20, 30, 40);

With polymorphism, the type of a subclass can be assigned to that of a superclass. This is shown in the following code, which is acceptable in TypeScript:

var boxObj : Box;

boxObj = new BoxWeight(10, 20, 30, 40);

In addition, if a function's parameter is expected to be of a specific class, it can be set to any object of any derived class.

 


All Chapters
Author