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 :
class Student{ constructor(private name: string, private rollno: string) { } }
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:
class Student{ private name: string; private rollno: string; constructor(name: string, rollno: string) { this.name = name; this.rollno = rollno; }
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:
var student = new Student("ajay","A005);
Leave a Reply