Click here to Skip to main content
13,150,178 members (60,427 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

7K views
1 bookmarked
Posted 16 Sep 2015

Typescript – Classes – Constructors

, 16 Sep 2015
Rate this:
Please Sign up or sign in to vote.
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

You may also be interested in...

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.170924.2 | Last Updated 16 Sep 2015
Article Copyright 2015 by Anooj Nair
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid