Use of Constructor in TypeScript

In this article I am going to explain how to use a constructor in TypeScript.

Constructor in TypeScript

 
Constructors are identified with the 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
  1. constructor(ParameterList(Optional)) {  
  2.   ................  
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 the Constructor program:
 

ExampleOfConstructor.ts

  1. class MyExample {  
  2.  public Fname: string;  
  3.  public Lname: string;  
  4.  constructor(Fname: string, Lname: string) {  
  5.   this.Fname = Fname;  
  6.   this.Lname = Lname;  
  7.   alert("Company name=" + this.Fname + " " + this.Lname);  
  8.  }  
  9. }  
  10. window.onload = () => {  
  11.  var data = new MyExample("Mcn""Solution");  
  12. }  
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

  1. < !DOCTYPEhtml >  
  2.  <  
  3.  htmllang = "en"  
  4. xmlns = "http://www.w3.org/1999/xhtml" >  
  5.  <  
  6.  head >  
  7.  <  
  8.  metacharset = "utf-8" / >  
  9.  <  
  10.  title > TypeScript HTML App < /title>  
  11.  <  
  12.  linkrel = "stylesheet"  
  13. href = "app.css"  
  14. type = "text/css" / >  
  15.  <  
  16.  scriptsrc = "app.js" > < /script>  
  17.  <  
  18.  /head>  
  19.  <  
  20.  body >  
  21.  <  
  22.  h1 > Example of Constructor < /h1>  
  23.  <  
  24.  divid = "content" / >  
  25.  <  
  26.  /body> <  
  27.  /html>  

app.js

  1. var MyExample = (function() {  
  2.  function MyExample(Fname, Lname) {  
  3.   this.Fname = Fname;  
  4.   this.Lname = Lname;  
  5.   alert("Company name=" + this.Fname + " " + this.Lname);  
  6.  }  
  7.  return MyExample;  
  8. })();  
  9. window.onload = function() {  
  10.  var data = new MyExample("Mcn""Solution");  
  11. };  
Output:
 
constructor2-in-TypeScript.jpg