Monday, November 19, 2012

JavaScript Development with TypeScript

TypeScript is a language for application-scale JavaScript development. It gives you type checking, explicit interfaces and easier module exports. The main advantages of the generated JavaScript file of the TypeScript are;

  • Any browser
  • Any host
  • Any OS
According to Somasegar "TypeScript is a super set of JavaScript that combines type checking and static analysis, explicit interfaces, and best practices into a single language and compiler. TypeScript  enables great tooling experiences for JavaScript development."

You can use TypeScript Play ground to check how this works on. But this post describes how to work on TypeScript using Visual Studio. First install the plugin for the VS 2012.

Create a TypeScript project.
Add a TypeScript file called customer.ts. Related customer.js file also in there.
Add the customer.js file reference to the default.htm file.
In the customer.ts file create a class called customer. Add two variables firstName as string and age as number.
Current typescript version is 0.8.1. So it's not generating the JavaScript while typing the TypeScript file. So you have to build the project. Then you can view the generated JavaScript.
Then add a constructor for the customer. firstName and the age properties can be set in the constructor. But last name has declared with public key. That means the customer class contains a property called lastName and it'll automatically set the values passed to constructor. The mobileNo is a nullable type of argument.
We can add a method called getFullName. Now we should check how to call the properties and the methods in the customer class. Declare a customer object and in the window.onmousemove event call a function.
You can see the output as follows.
TypeScript supports for the inheritance. If we extends a class, in the sub class we must call the super class's constructor. 
Also Typescript support for the interfaces. If we implements an interface we must implement the methods in that interface.
We can modularising the TypeScript classes. 
In order to avoid the long namespace we can use the import statements. 
Also the TypeScript have features like Refactor - Rename, Go to definition, Go to declaration, Find All references. Those are really useful features that are not in JavaScript.
As you can see TypeScript brings you useful features in to JavaScript and ultimately syntax friendly way of development.

No comments:

Post a Comment