How to Declare Constructors in TypeScript Angular 2


Constructors in TypeScript

In this post we will see how to create a constructors in TypeScript angular 2. S0 here we have same Point class which we used in tutorial for declaring class in Typescript.  Only code we added is for the constructor as given below. 

We can declare a constructor in TypeScript using ‘constructor’ keyword and we can have only one constructor. If you are using java you have feature of having multiple constructors inside a class but in typescript you can have only one constructor.  

Lets run this above code to see the output.

How to make Constructor Optional in TypeScript?

We can use ‘?‘ to make a constructor parameter optional.

NOTE: All parameters right to optional parameter also need to be changed to optional else it will show you compilation error message.

In above code we are passing only one parameter in constructor which is acting like a overloaded constructor feature only. Now lets run this code.