Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

JavaScript with TypeScript: How to Develop Large Scale Applications

In this article, we will discuss TypeScript. We will discuss the TypeScript features which consist of OOP characteristics such as classes, modules and interfaces which are proposed features of ECMAScript6.

TypeScript is free and open source programming language. This language is designed for large scale JavaScript development; it supports any host, any browser and any OS. It is maintained and developed by Microsoft. It is a first superset of JavaScript. Its syntax is based on ECMAScript 4 and ECMAScript 6 proposals.

  • A file of TypeScript is saved with .ts extension,
  • Later when TypeScript compiles the files, then the entire TypeScript file gets generated as regular JavaScript (.js) file.
  • It is syntactically very similar to Jscript.NET. It integrates with several tools such as Emacs, Visual Studio, Sublime text etc.

History

TypeScript is designed and developed by Microsoft. It was initially released on October 1st 2012. It was created by Anders Hejlsberg (the creator of the C# language) and his team at Microsoft. TypeScript is licensed under the Apache License 2.0. It is influenced by java, JavaScript and C#. The Filename extension for TypeScript is .ts.

The TypeScript code can be compiled in the following two ways:

  • Install the TypeScript Editor plug-in for visual studio 2012 which helps to write the TypeScript code within the visual studio IDE. OR
  • TypeScript code can be written in any text editor and compile using TypeScript command line compiler via npm (Node.js package manager).

Here we are going to use the second way i.e. npm (Node.js package manager) which is very simple and easy to understand.

Installation

The following command line via npm should be written in the command prompt to install the TypeScript compiler.

  npm install -g typescript
  

After writing the above line in command prompt, you will get the following lines as shown in figure1.

Figure 1. cmd

Example:

The following Listing 1 is a simple example of a TypeScript code using command prompt.

In text editor you can write the following javascript code.

Listing 1.sample.ts

  function greeter(person) {
      return "Welcome to " + person;
  }
  var object = "New World";
  document.write(greeter(object));
  

  • Save the above file as sample.ts. Here .ts is the extension used to save the typescript file.
  • In the command prompt, run the following TypeScript compiler.

  C:\> tsc sample.ts
  

After compiling the above sample.ts file, it will generate a javascript file sample.js file with the same name as of source file. This can then be loaded by the browser. If there are any compilation errors, then it will get displayed on the command prompt. Below is a JavaScript file:

Listing 2. sample.js

  function greeter(person) {
      return "Welcome to " + person;
  }
  var object = "New World";
  document.write(greeter(object));
  

The above Listing 2 file will automatically get generated when the typescript file is compiled in the command prompt.

Listing 3. sample.html

  <!DOCTYPE html>
     <head>
        <title> Simple Example of TypeScript </title>
     </head>
     <body>
               <script src="greeter.js"></script>
     </body>
  </html>
  

Above, we have created a simple html file and referred the JavaScript file sample.js file into it.

We can continue to write or modify the TypeScript code in the .ts file. The JavaScript file .js will automatically keep on detecting the changes and overwriting the .js file every time we save the original file. Whenever changes are done in your .ts file then you have to go to command prompt and execute the above line and then you could see the changes occurred in .js files.

Output

  • Save the file as sample.html in your system.
  • Just open the file in the browser and you will see the output as shown in the Figure 2 :

Figure 2. Sample_output

Features of TypeScript

Type annotations

Type annotations are an optional static typing. It supports built-in JavaScript types such as string, number, void, null, Boolean and undefined. In TypeScript, Type annotations are a lightweight way to record the variables or functions. It supports the typed array; return type of function can be inferred. If no type is inferred then it is default to the dynamic any type.

Example:

Listing 4 shows a simple example of how to express the type annotation as a part of the function parameter.

Listing 4. TypeAnnotation.ts

  function area(width: number, height: number) {
      var area = width + height;
      return "Total height and width of the Square is  = " + area + " cm ";
  }
  document.write(area(15, 15));
  

· Save the above file as TypeAnnotations.ts.

· In the command prompt, run the following TypeScript compiler.

  C:\> tsc TypeAnnotations.ts
  

In Listing 5 JavaScript file will automatically get generated when the typescript file is compiled in the command prompt and it will look like as shown below.

Listing 5. TypeAnnotation.js

  function area(width, height) {
      var area = width + height;
      return "Total height and width of the Square is  = " + area + " cm ";
  }
  document.write(area(15, 15)); 
  

A simple html file, referring the JavaScript file TypeAnnotations.js file

Listing 6. TypeAnnotation.html

  <!DOCTYPE html>
     <head>
        <title> Type annotations Example</title>
     </head>
     <body>
          <script src="TypeAnnotaions.js" ></script>
     </body>
  </html>
  

Details of code:

  • In Listing4, we have express the type annotation as a part of the function parameter.
  • function area(width: number, height: number) line indicate the types of values you can pass to the function.
  • var area = width + height; line is used to calculate the area by using width and height values.
  • return "Total height and width of the Square is = " + area + " cm "; line returns the calculated values.
  • document.write(area(15, 15)); line is to display the text directly into the HTML document.
  • The .ts Listing4 file is compiled in the command prompt and .js Listing5 file gets generated.
  • line is used for referring the .js file in html, which gets created after compilation of typescript file.

Output

· Save the file as TypeAnnotations.html in your system.

· Just open the file in the browser and you will see an output as shown in the Figure 3 in the browser.

Figure 3. TypeAnnotations_output

Interfaces

Interfaces help in providing the information about the shape of the data or values you work on. It is a pure compile-type construct and has no run time representation; it is most flexible way to describe the type. Interfaces are designed for development tooling support only.

Example:

Listing 7 shows a simple example of interfaces that describe the name as an object.

Listing 7. Interfaces.ts

  interface Person {
      name: string;
      age: number;
      gender: string;
  } 
  function detail(person : Person) {
      var detail = person.age;
      return "My name is" + person.name + " and I'm " + detail + " Years old<br/>";
  } 
  document.write( detail( {name: "Vedant", age: 3, gender: "m"} ) );
  document.write( detail( {name: "Vihan", age: 5, gender: "m"} ) ); 
  

· Save the above file as Interface.ts.

· In the command prompt, run the following TypeScript compiler.

  C:\> tsc Interface.ts
  

In Listing 8 JavaScript file will automatically get generated when the typescript file is compiled in the command prompt and it will look like as shown below.

Listing 8. Interfaces.js

  function detail(person) {
      var detail = person.age;
      return "My name is" + person.name + " and I'm " + detail + " Years old<br/>";
  }
  document.write(detail({ name: "Vedant", age: 3, gender: "m" }));
  document.write(detail({ name: "Vihan", age: 5, gender: "m" })); 
  

A simple html file, referring the JavaScript file Interfaces.js file

Listing 9. interfaces.html

  <!DOCTYPE html>
     <head>
        <title> Interfaces Example</title>
     </head>
     <body>
  <script src="Interfaces.js" ></script>
     </body>
  </html>
  

Details of code:

  • In Listing7, we have declare an interfaces that describe the name as an object with optional gender object.

·

  interface Person {
      name: string;
      age: number;
      gender: string;
  } 
  

Here we are defining interfaces with various properties along with optional property and data-type.

  • var detail = person.age; line is used to describe the age value.
  • return "My name is" + person.name + " and I'm " + detail + " Years old"; line returns the complete detail of the person.

·

  document.write(detail({ name: "Vedant", age: 3, gender: "m" }));
  document.write(detail({ name: "Vihan", age: 5, gender: "m" }));
  

This line is to display the details directly into the HTML document.

Output

  • Save the file as interface.html in your system.
  • Just open the file in the browser and you will see an output as shown in the Figure 4 in the browser.

Figure 4. interfaces_output

Classes

Classes include a static method and follow the ECMAScript6 proposal. It supports single-parent inheritance. The keyword class in typescript provides very familiar syntax for generating constructor functions and the interfaces containing all the instance methods and properties of the class. It specifies public and private member accessibility. The private member can be accessed within the class body and includes a declaration. By default its accessibility is public.

Example

Listing 10 shows a simple example of classes using the member accessibility.

Listing10. classes.ts

  class Person {
      private name: string;
      private age: number;
      private gender: string;
   
      constructor ( name: string, age: number) {
          this.age = 15;
          this.name="Akshata";
          this.gender="Female"
      };
      
     details() {
          return "This is  " + this.name + " and she is " + this.age +  "Years old<br/> ";
      }
  }
  var person = new Person("person");
   
  document.write( person.details() );
  document.write('Name of the person: ' + person.name+ "<br>");
  document.write('Age: ' + person.age+ "<br>");
  document.write('Gender: ' + person.gender);
  

· Save the above file as classes.ts.

· In the command prompt, run the following TypeScript compiler.

  C:\> tsc classes.ts
  

In Listing 11 JavaScript file will automatically get generated when the typescript file is compiled in the command prompt and it will look like as shown below.

Listing 11. classes.js

  var Person = (function () {
      function Person(name, age) {
          this.age = 15;
          this.name = "Akshata";
          this.gender = "Female";
      }
      ;
      Person.prototype.details = function () {
          return "This is  " + this.name + " and she is " + this.age + "Years old<br/> ";
      };
      return Person;
  })();
  var person = new Person("person");
  document.write(person.details());
  document.write('Name of the person: ' + person.name + "<br>");
  document.write('Age: ' + person.age + "<br>");
  document.write('Gender: ' + person.gender);
  

A simple html file, referring the JavaScript file classes.js file

Listing12. interfaces.html

  <!DOCTYPE html>
     <head>
        <title> Classes Example</title>
     </head>
     <body>
  <script src="classes.js" ></script>
     </body>
  </html>
  

Details of code:

  • · In the example Listing10, we have created a class and shown a type of argument.

  class Person {
      private name: string;
      private age: number;
      private gender: string;
   
     constructor ( name: string, age: number) {
          this.age = 15;
          this.name="Akshata";
          this.gender="Female"
      };
   

Here we are defining class Person; it has three properties i.e. name, age and gender by specifying private member accessibility. We have defined constructor functions similar to instance member of classes by using this keyword.

  details() {
          return "This is  " + this.name + " and she is " + this.age +  "Years old<br/> ";
      }
  

This function is used to return the data values.

document.write( person.details() line is to display the complete details of the person directly into the HTML document.

Output

  • Save the file as classes.html in your system.
  • Just open the file in the browser and you will see an output as shown in the Figure 5 in the browser.

Figure 5. classes_output

Arrow function expressions

Arrow function expression is a new feature in ECMAScript6. It is similar to the lambda expression. It is a compact way to define functions. It binds the keyword this. It has also been designed well to work with callback functions. Arrow function has a shorter syntax as compared to function expressions and it is also known as fat arrow function.

Example

Listing 13 shows a simple example of arrow function expression.

Listing 13. arrowFunction.ts

  var person = {
      name: "Mr Bool",
     
      arrow: function() {
          document.write('Welcome: ' + this.name);
   
          setTimeout( () => {
              document.write("I'm  " + this.name + "!");
          }, 2000);
      }
  };
   
  person.arrow();
  

  • Save the above file as arrowFunction.ts.
  • In the command prompt, run the following TypeScript compiler.

  C:\> tsc arrowFunction.ts
  

In Listing 14 JavaScript file will automatically get generated when the typescript file is compiled in the command prompt and it will look like as shown below.

Listing 14. arrowFunction.js

  var person = {
      name: "Mr Bool",
      arrow: function () {
          var _this = this;
          document.write('Welcome: ' + this.name);
          setTimeout(function () {
              document.write("I'm  " + _this.name + "!");
          }, 2000);
      }
  };
  person.arrow();
  

A simple html file, referring the JavaScript file arrowFunction.js file

Listing 15. arrowFunction.html

  <!DOCTYPE html>
     <head>
        <title> Arrow Function Expression Example</title>
     </head>
     <body>
          <script src="arrowFunction.js" ></script>
     </body>
  </html>
  

Details of code:

  • In the example in Listing13, we have used an arrow function expression.

  var person = {
     name: "Mr Bool",
  

Here variable name is defined.

  arrow: function() {
                      document.write('Welcome: ' + this.name);
               setTimeout( () => {
                      document.write("I'm  " + this.name + "!");
               }, 2000);
         }
  

Here setTimeout is a call back function to refer the name property. => is a arrow function expression defined by replacing the function(). If you define function() instead of => then this.name will not display any name in the output, it will show as empty.

Output

  • Save the file as arrowFunction.html in your system.
  • Just open the file in the browser and you will see an output as shown in the Figure 6 and Figure 7 in the browser.
  • Figure 6 is the output you get after opening your file in the browser and Figure 7 image you will get after few seconds as we have used the setTimeout function in the example.

Figure 6. arrowexpression_output

Figure 7. arrowexpression1_output

Type inference

Type Inference is a feature to infer the types of some or all expressions where there is no explicit type annotation. Setting parameter default values, initializing variables and members and determining function return types is a kind of inferences that takes place. It is Functional programming language; the compiler needs minimum information to figure out the variable or expression type.

Example

Listing 16 shows a simple example of type inference using common type.

Listing16. typeInference.ts

  interface Person {
      name: string;
      Gender: string;
      telephone: string;
  }
   
  interface Staff {
      Manager: Person;
      Employee: Person;
      hr: Person;
  }
   
  var staff: Staff = {
      Manager: {name: 'John', Gender: 'Male', telephone: '0898 007' },
      Employee: {name: 'Luce', Gender: 'Female', telephone: '0898 008'},
      hr: { name: 'Jack', Gender: 'Male', telephone: '0898 009' }
  };
  function showName(person: Person) {
      document.write(person.name);
      document.write('    ' +person.Gender+ "<br>");
  }
   
  showName(staff.Manager);
  showName(staff.Employee);
  showName(staff.hr);
  

  • Save the above file as typeInference.ts.
  • In the command prompt, run the following TypeScript compiler.

  C:\> tsc typeInference.ts
  

In Listing 17 JavaScript file will automatically get generated when the typescript file is compiled in the command prompt and it will look like as shown below.

Listing 17. typeInference.js

  var staff = {
      Manager: { name: 'John', Gender: 'Male', telephone: '0898 007' },
      Employee: { name: 'Luce', Gender: 'Female', telephone: '0898 008' },
      hr: { name: 'Jack', Gender: 'Male', telephone: '0898 009' }
  };
  function showName(person) {
      document.write(person.name);
      document.write('    ' + person.Gender + "<br>");
  }
  showName(staff.Manager);
  showName(staff.Employee);
  showName(staff.hr);
  

A simple html file, referring the JavaScript file typeInference.js file

Listing 18. typeInference.html

  <!DOCTYPE html>
     <head>
        <title> Type Inference Example</title>
     </head>
     <body>
          <script src="typeInference.js" ></script>
     </body>
  </html>
  

Details of code:

  • In the example in Listing16, we have used type inference using the common type expression.

  interface Person {
      name: string;
      Gender: string;
      telephone: string;
  }
   
  interface Staff {
      Manager: Person;
      Employee: Person;
      hr: Person;
  }
  

Here, we have included interfaces that describe Person and Staff as an object and with defined properties with data types i.e. name, gender and telephone.

  var staff: Staff = {
      Manager: {name: 'John', Gender: 'Male', telephone: '0898 007'},
      Employee: {name: 'Luce', Gender: 'Female', telephone: '0898 008'},
      hr: { name: 'Jack', Gender: 'Male', telephone: '0898 009' }
  };
  

Here staff is been inferred as a Staff.

  showName(staff.Manager);
  showName(staff.Employee);
  showName(staff.hr);
  

This line is used to show the information of the particular staff member.

Output

  • Save the file as typeInferences.html in your system.
  • Just open the file in the browser and you will see an output as shown in the Figure 8 in the browser.

[Figure 8. typeInference_output]

Generic

Generic is a tool for creating reusable components in toolbox. It can create a component which is able to work on any variety of types. It can operate on any kind of array and the kind of array is returned on the base of callback function it is passed. In generic identity function, it explores the type of function itself and create generic interface.

Example

Listing 19 shows a simple example of generic in typescript.

Listing 19. generic.ts

  class InstanceLoader {
      static getInstance<T>(context: Object, name: string, ...args: any[]) : T {
          var instance = Object.create(context[name].prototype);
          instance.constructor.apply(instance, args);
          return <T> instance;
      }
  }
  interface Person {
          name: string;
          gender: string;
  }
  class Details {
          public name = 'Jass';
          gender='Female';
          
  }
  var details = InstanceLoader.getInstance<Person>(window, 'Details', 'Some input', 'Some more input');
  document.write('Name: '+details.name+ '<br/>');
  document.write('Gender: '+details.gender);
  

  • Save the above file as generic.ts.
  • In the command prompt, run the following TypeScript compiler.

  C:\> tsc generic.ts
  

Listing 20 JavaScript file will automatically get generated when the typescript file is compiled in the command prompt and it will look like as shown below.

Listing 20. generic.js

  var InstanceLoader = (function () {
      function InstanceLoader() {
      }
      InstanceLoader.getInstance = function (context, name) {
          var args = [];
          for (var _i = 2; _i < arguments.length; _i++) {
              args[_i - 2] = arguments[_i];
          }
          var instance = Object.create(context[name].prototype);
          instance.constructor.apply(instance, args);
          return instance;
      };
      return InstanceLoader;
  })();
  var Details = (function () {
      function Details() {
          this.name = 'Jass';
          this.gender = 'Female';
      }
      return Details;
  })();
  var details = InstanceLoader.getInstance(window, 'Details', 'Some input', 'Some more input');
  document.write('Name: ' + details.name + '<br/>');
  document.write('Gender: ' + details.gender);
  

A simple HTML file, referring the JavaScript file generic.js file

Listing 21. generic.html

  <!DOCTYPE html>
     <head>
        <title> Generic Example</title>
     </head>
     <body>
                 <script src="generic.js" ></script>
     </body>
  </html>
  

Details of code:

  • In the example Listing18, we have used generic type parameter.

  class InstanceLoader {
      static getInstance<T>(context: Object, name: string, ...args: any[]) : T {
          var instance = Object.create(context[name].prototype);
          instance.constructor.apply(instance, args);
          return <T> instance;
      }
  }
  

In this line we have created instance class and methods. Here T is a type variable.

  var details = InstanceLoader.getInstance<Person>(window, 'Details', 'Some input', 'Some more input');
  

This line defines generic instance function. Here we have passed all the arguments with the type argument to the function. We have explicitly set T to be string which is denoted using < > to the argument.

Output

  • Save the file as generic.html in your system.
  • Just open the file in the browser and you will see an output as shown in the Figure 9 in the browser.

[Figure 9. generic_output]

Modules

Module is to organize the classes and interfaces for proper maintainability. It prevents global variable naming collision. Typescript categorizes the module between external and internal modules. An internal module is based on syntax of ECMAScript6 and external module is like AMD or CommonJS.

Example

Listing 22 shows a simple example of modules in TypeScript.

Listing 22. modules.ts

  module Validation {
      export interface NumberValidator {
          isAcceptable(s: number): boolean;
      }
   
      var lettersRegexp = /^[A-Za-z]+$/;
      var numberRegexp = /^[0-9]+$/;
   
      export class NumberOnlyValidator implements NumberValidator {
          isAcceptable(s: number) {
              return numberRegexp.test(s);
          }
      }
  }
   
  var numbers = ['545121', 'john'];
   
  var validators: { [s: number]: Validation.NumberValidator; } = {};
  validators[' number only<br>'] = new Validation.NumberOnlyValidator();
   
  numbers.forEach(s => {
      for (var name in validators) {
          document.write('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches' : ' does not match') + name);
      }
  });
  

  • Save the above file as generic.ts.
  • In the command prompt, run the following TypeScript compiler.

  C:\> tsc modules.ts
  

In Listing 23 JavaScript file will automatically get generated when the typescript file is compiled in the command prompt and it will look like as shown below.

Listing 23. modules.js

  var Validation;
  (function (Validation) {
      var lettersRegexp = /^[A-Za-z]+$/;
      var numberRegexp = /^[0-9]+$/;
      var NumberOnlyValidator = (function () {
          function NumberOnlyValidator() {
          }
          NumberOnlyValidator.prototype.isAcceptable = function (s) {
              return numberRegexp.test(s);
          };
          return NumberOnlyValidator;
      })();
      Validation.NumberOnlyValidator = NumberOnlyValidator;
  })(Validation || (Validation = {}));
  var numbers = ['545121', 'john'];
  var validators = {};
  validators[' number only<br>'] = new Validation.NumberOnlyValidator();
  numbers.forEach(function (s) {
      for (var name in validators) {
          document.write('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches' : ' does not match') + name);
      }
  });
  

A simple html file, referring the JavaScript file modules.js file

Listing 24. Modules.html

  <!DOCTYPE html>
     <head>
        <title> Modules Example</title>
     </head>
     <body>
          <script src="modules.js" ></script>
     </body>
  </html>
  

Details of code:

  • In the example in Listing22, we have used a module with a small set of number validators.
  • export interface NumberValidator{} line is used to internal aspects of module accessible outside the module using the keyword export.

  var lettersRegexp = /^[A-Za-z]+$/;
      var numberRegexp = /^[0-9]+$/;
  

Line is an implementation detail that is not visible outside the module.

Output

  • Save the file as modules.html in your system.
  • Just open the file in the browser and you will see an output as shown in the Figure 10 in the browser.

Figure 10. Modules_output

Conclusion

In this article, we discussed some features of TypeScript and how the TypeScript file is installed through the command prompt and how the files of TypeScript is saved and executed in the browser. The Source code of the examples is attached with this article. TypeScript is best of many JavaScript front-end.

Links

TypeScript official website

http://www.typescriptlang.org/



I''m a full stack developer with around 10+ yrs of experience. I enjoy writing technical articles on upcoming technical trends.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login