How to Declare Classes in TypeScript Angular 2
In this post we will see how to declare a class in TypeScript angular 2. In this below code window you can see we have declared class Point with two variables ‘x’ and ‘y’. We have one method also inside Point class which will print both the point values of object.
class Point { x: number; y: number; doSomething() { console.log('Point X: '+this.x); console.log('Point Y: '+this.y); } }
Initializing the Class in TypeScript
In this below code snippet we are creating one variable point with is of Type Point class. Then we are allocating memory or creating object of type Point by using new keyword like any other object oriented language.
let point: Point; point = new Point(); point.x=1; point.y=2; point.doSomething();
We are using point variables to assign values to object variables ‘x’x and ‘y’. At the end we are calling doSomething() method of point object we just created. Below is the result of above code.
let point: Point; point = new Point(); point.x=1; point.y=2; point.doSomething();
Leave a Reply