ARTICLE

Use of Constructor in TypeScript

Posted by Sharad Gupta Articles | TypeScript November 21, 2012
In this article I am going to explain how to use a constructor in TypeScript.
Reader Level:

 Constructor in TypeScript

Constructors are identified with keyword "constructor". A Constructor is a special type of method of a class and it will be automatically invoked when an instance of the class is created. A class may contain at least one constructor declaration. If a class has no constructor, a constructor is provided automatically. A class can have any number of constructors. When you are using the attribute public or private with constructor parameters, a field is automatically created, which is assigned the value.

Syntax

constructor(ParameterList(Optional)) { ................//body}

The following example tells you, how to use a constructor in TypeScript. Use the following procedure to create a program using a constructor.

Step 1

Open Visual Studio 2012 and click on "File" menu -> "New" -> "Project". A window will be opened. Specify the name of your application, like "ExampleOfConstructor". Your application will look like:

constructor1-in-TypeScript.jpg

Then click on the OK button.

Step 2

After Step 1 your project has been created. The Solution Explorer, which is at the right side of Visual Studio, contains the js file, ts file, css file and html files.

Step 3

The code of Constructor program:

ExampleOfConstructor.ts

class MyExample {

public Fname: string;

public Lname: string;

constructor (Fname: string, Lname: string) {

this.Fname = Fname;

this.Lname = Lname;

alert("Company name="+this.Fname+" "+this.Lname);

}

}

window.onload = () =>

{

var data = new MyExample ("Mcn","Solution");
}


Note
In the above declared program, I have the MyExample class, with a constructor which takes two string value as arguments. When I create an instance of the class (MyExample), the constructor is automatically executed.

default.html
 

<!DOCTYPEhtml>

 

<htmllang="en"xmlns="http://www.w3.org/1999/xhtml">

<head>

<metacharset="utf-8"/>

<title>TypeScript HTML App</title>

<linkrel="stylesheet"href="app.css"type="text/css"/>

<scriptsrc="app.js"></script>

</head>

<body>

<h1>Example of Constructor</h1>

 

<divid="content"/>

</body>
</
html>


app.js

 

var MyExample = (function () {

function MyExample(Fname, Lname) {

this.Fname = Fname;

this.Lname = Lname;

alert("Company name=" + this.Fname + " " + this.Lname);

}

return MyExample;

})();

window.onload = function () {

var data = new MyExample("Mcn","Solution");
};

 

Output:

constructor2-in-TypeScript.jpg

COMMENT USING