Constructor chaining in TypeScript

Typescript constructor: Before going to understand the constructor chaining we first need to know what exactly the typescript constructor is.

In typescript constructor are define with keyword "constructor". A Constructor is a special type of function of typescript class and it will be automatically invoked when the first object of class is created.

Use of typescript constructor
Is to initialize variable of the class

Typescript constructor channing: Type script claases support single inheritance same as other language.But, here we using the extends keyword to inherit classes in typescript.

  Class employee extends manager
             |                             |
             |                             |
     derive class                base class

Constructor chaining is just a process in which if you have a constructor in your class(derive class), then you need to call base class constructor by your constructor. Here constructor calling is different we are using the super keyword [super(d)].

class manager
        return this.duration;
class employee extends manager
    empdura :number;
    constructor (du:number,d:number)
        return this.empdura;

var emp=new employee(101,69);

When to use super keyword in typescript

1.When ever we need to call constructor of the base class in case of constructor chaining.

2.In most cases, to access the base class functions, the “super” keyword is specified inside those functions which have same name as base class’s functions has in a derived class.

3.In a derived class, the overridden/hidden functions of a base class can be accessed/called through a “super” keyword reference because along with a base class constructor the base class functions can  also be accessed/refer through “super” keyword.

4.If a constructor is defined only in derived class, TypeScript compiler will generate a compile-time error until we use a “super ()” keyword in it.


Next Post »