Click here to Skip to main content
15,885,088 members
Articles / All Topics

Typescript – Classes – Constructors

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
16 Sep 2015CPOL 13.2K   1   1
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)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionLess Code Pin
Rob Norris21-Oct-15 4:19
Rob Norris21-Oct-15 4:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.