Constructor chaining and inheritance in TypeScript

Typescript constructor and inheritance


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

Constructor chaining


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

Use of typescript constructor

Is to initialize a variable of the class

Typescript constructor Channing: 

Typescript classes support single inheritance the same as other languages.But, here we use 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.Whenever we need to call the constructor of the base class in case of constructor chaining.

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

3. In a derived class, the overridden/hidden functions of a base the 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 the derived class, the TypeScript compiler will generate a compile-time error until we use a “super ()” keyword in it.



Reference

Post a Comment

Post a Comment (0)

Previous Post Next Post