How to Declare Constructors in TypeScript Angular 2
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.
class Point { x: number; y: number; constructor(x:number,y:number){ this.x=x; this.y=y; } doSomething() { console.log('Point X: '+this.x); console.log('Point Y: '+this.y); } }
Lets run this above code to see the output.
PS C:\Users\AnilKumar\ts-hello> tsc code-main.ts PS C:\Users\AnilKumar\ts-hello> node code-main.js Point X: 1 Point Y: 2 PS C:\Users\AnilKumar\ts-hello>
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.
class Point { x: number; y: number; constructor(x?:number,y?:number){ this.x=x; this.y=y; } doSomething() { console.log('Point X: '+this.x); console.log('Point Y: '+this.y); } } let point: Point; point = new Point(1); point.doSomething();
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.
PS C:\Users\AnilKumar\ts-hello> tsc code-main.ts PS C:\Users\AnilKumar\ts-hello> node code-main.js Point X: 1 Point Y: undefined PS C:\Users\AnilKumar\ts-hello>