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.


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:


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:


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");

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.







<title>TypeScript HTML App</title>





<h1>Example of Constructor</h1>






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");




Employers - Post Free Jobs