Classes and constructors are the bread and butter for any object oriented programming language. Following is the code sample on how to create classes and constructors in typescript. Class
keyword is used to create a class.
class Rectangle {
length: number;
breadth:number;
setLength(value:number)
{
this.length = value;
}
setBreadth(value:number)
{
this.breadth = value;
}
Area() {
return this.length * this.breadth;
}
}
var rect1 = new Rectangle();
rect1.setLength(10);
rect1.setBreadth(20);
alert(rect1.Area());
The following creates a new object of type Rectangle
.
var rect1 = new Rectangle();
Typescript – Constructors
The above code can also be done using a constructor, following is how you would create a typescript constructor. The keyword to use here is constructor
.
class Rectangle {
length: number;
breadth:number;
constructor(len: number,bre:number) {
this.length = len;
this.breadth = bre;
}
Area() {
return this.length * this.breadth;
}
}
var rect1 = new Rectangle(10,20);
alert(rect1.Area());
Feel free to play around with typescript using the playground .
The post Typescript – Classes – Constructors appeared first on Tech Musings - Anooj nair.