Click here to Skip to main content
14,241,676 members

Typescript – Classes – Constructors

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

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.

License

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

Share

About the Author

Anooj Nair
Software Developer
India India
No Biography provided

Comments and Discussions

 
QuestionLess Code Pin
Rob Norris21-Oct-15 4:19
memberRob 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.

Technical Blog
Posted 16 Sep 2015

Tagged as

Stats

10K views
1 bookmarked