×
☰ See All Chapters

TypeScript Constructor

  • Constructor is a special block which is used to initialize an object. Objects of class can be created by invoking constructor or without invoking constructor objects cannot be created.  

  • Constructor must be named constructor. 

class Box {

    constructor() {

    }

}

  • Each class can have only one constructor. Constructor overloading is not allowed. If no constructor is defined in code, a constructor with no arguments (a no-arg constructor) will be created. 

  • Constructors shoud be always public, private or protected modifiers can't be used. 

  • When creating objects of any class, consturcor should be invoked and while calling constaructor arguements should be passed if constaructor has parameters 

  • Constructor can be invoked only with the help of “new” keyword and can never be accessed with the help of dot (“.”) operator or it can never be invoked by an object. 

  • Constructor is always executed only once during the creation of every new object. 

  • Constructors are not inherited into sub class (sub class will be studied in later chapters). 

Access modifier to constructor’s parameter

If a constructor's parameter has an access modifier (public, protected, or private), the corresponding property doesn't need to be declared in the class.  In the below Box definition, width and length properties were declared in the class and initialized in the constructor. By adding access modifiers to the constructor's parameters, the following definition accomplishes the same result with much less code.

class Point {

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

        this.width = width;

        this.length = length;

    }

}

If constructor's parameter has an access modifier and if same properties are declared in a class, it results into Duplicate Identifier error.

typescript-constructor-0
 

All Chapters
Author