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.

See:
  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
{
    duration:number;
    constructor(d:number)
    {
        this.duration=d;
    }
    work():number
    {
        return this.duration;
    }
}
class employee extends manager
{
    empdura :number;
    constructor (du:number,d:number)
    {
        super(d);
        this.empdura=du;
    }
    Mywork():number
    {
        return this.empdura;
    }

}
var emp=new employee(101,69);
console.log(emp.work());
console.log(emp.Mywork());




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.


Reference

Previous
Next Post »