Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

Typescript – Classes – Constructors

0.00/5 (No votes)
16 Sep 2015CPOL 13.5K  
Typescript – Classes – Constructors

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.

C#
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.

C#
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.

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)