Constructor in TypeScript

TypeScript is used for object oriented programming.ECMAScript 6 also supports object oriented programming.

Like other object oriented languages ,classes in typescript have a constructor.If we don’t explicitly specify constructor
then it will have a default constructor.This default constructor initializes the properties of class with default values.

A constructor is declared in typescript using the following syntax :

If you have worked with other object oriented languages then you can immediately see the difference in the constructor definition above.
1.Unlike other languages constructor is declared using the keyword constructor.
2.Properties are not required to be explicitly initialized with the constructor parameters.These are called Parameter properties
The above constructor declaration is identical to the following:

If we declare constructor parameter using the access modifier private then it initializes private property.
We can create an object of the class using similar syntax as other languages:

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *