Introduction
Modern web applications rely heavily on client side scripting for various needs ranging from validations to Ajax calls. Many web developers who are more familiar with the server side programming model of ASP.NET find it difficult to quickly and efficiently use JavaScript. They will find TypeScript a nice addition to their skill-set. TypeScript is a superset of JavaScript that provides typed nature to your code. More importantly TypeScript code, when compiled gets converted into the same standard JavaScript. This means after compiling the TypeScript code you can use the resultant JavaScript in any browser that supports JavaScript. This article is intended to give you a quick overview of this new scripting language.
What is TypeScript?
Though JavaScript is widely used in web applications many developers find it uncomfortable to work with. The main problem is that the JavaScript program model and constructs are quite different than a modern language such as C#. For example, JavaScript lacks strong type checking of function parameters while making function calls. Creating and using classes and interfaces is quite difficult, unlike C# where the language is designed to supports these features. TypeScript tries to bridge this gap by providing typed nature to your JavaScript code. Using TypeScript you can create classes and interfaces quite easily in your JavaScript code. When you compile a TypeScript file the entire TypeScript code is converted into an equivalent JavaScript code. This JavaScript file can then be used in any HTML page just like any other JavaSript file. So, essentially using TypeScript in an ASP.NET application involves these steps:
- Write TypeScript code in a file usually having extension .ts
- Compile the TypeScript code using the TypeScript command line compiler or Visual Studio Editor plug-in.
- Refer the compiled output of the above step in HTML web pages, web forms or MVC views.
Installing TypeScript Editor Plug-in for Visual Studio 2012
You can write and compile TypeScript code in two ways:
- You can write the TypeScript code in any text editor and then compile it using the TypeScript command line compiler.
- You can make use of the TypeScript Editor plug-in for Visual Studio 2012 that allows you to write and compile TypeScript code from within the Visual Studio IDE.
Obviously, the second option is quick and easy for ASP.NET 4.5 developers and is what you will use in this article. The biggest advantage of using this editor is that is offers intellisense and in-line compilation that helps you to spot errors quickly.
To install the TypeScript editor plug-in for Visual Studio 2012, download it from here and then run the installation. The following figure shows the first screen of the TypeScript installation. The installation will install the TypeScript editor plug-in as well as the TypeScript command line compiler.
TypeScript Installer
Now, open Visual Studio 2012 and select File > New Project. In the new project dialog search for TypeScript to reveal a project template – “HTML Application with TypeScript.”
Search for TypeScript to reveal a project template
The newly created project has a simple structure as shown below:
Solution Explorer
Notice that there are two files added by default for you, viz. app.ts and app.js. The app.ts file contains your TypeScript code whereas the app.js file contains the compiled output of the .ts file. The app.ts file gets compiled and app.js file is created automatically when you compile the project. The app.ts file contains some dummy code. Delete all that code because you will write your own.
The TypeScript Command Line Compiler
Though the TypeScript editor for Visual Studio 2012 compiles the .ts file for you automatically, it is worthwhile to know the TypeScript command line compiler. The TypeScript command line compiler (tsc.exe) has the switches as shown in the following figure:
The TypeScript command line compiler
In its basic form you will use tsc.exe as follows:
tsc <.ts file path>
The above command accepts the source .ts file, compiles it and outputs a .js file with the name same as the source file name. If there are any compilation errors they will also be shown.
Creating a Simple TypeScript Application
Now it’s time to write some TypeScript code. In the code that follows you will create a simple class named CustomerContact. The CustomerContact class will inherit from a base class named Customer and will also implement an interface named IContact.
Open the app.ts file and add an interface named IContact as shown below:
interface IContact { firstname: string; lastname: string; email: string; }
The above piece of code uses interface keyword to create an interface named IContact. The IContact interface consists of three property declarations, viz firstname, lastname and email. Notice how TypeScript allows you to specify the data type of the individual properties (string in this case).
Next, add a class named Customer as shown below:
class Customer { address: string; constructor(public company:string,public country:string) { } }
The above code uses the class keyword to create a class named Customer. The Customer class has a property named address, which is of type string. Additionally, it has a constructor that takes two parameters, viz. company and country. While using the Customer class later in the code it will have in all three properties – address, company and country. Two out of these three (company and country) will be set through the parameterized constructor. The address property will need to assigned separately.
Now, let’s create the CustomerContact class that inherits from Customer base class and implements IContact interface. Have a look at the following code:
class CustomerContact extends Customer implements IContact{ firstname: string; lastname: string; email: string; active: bool; constructor(firstname:string,lastname:string,company:string,country:string) { super(company, country); this.firstname = firstname; this.lastname = lastname; } GetContactDetails() { var obj = {fullname:this.firstname + ' ' + this.lastname,emailaddress:this.email}; return obj; } }
The CustomerContact class “extends” Customer base class and “implements” IContact interface. Recollect that the IContact interface defines three properties (firstname, lastname and email) and you must have them in CustomerContact again in order to implement IContact. Additionally, the CustomerContact has one more property – active of boolean type.
The CustomerContact class also has a parameterized constructor. Notice that this time the constructor doesn’t use public keyword for the parameters. Doing so means that the parameters merely pass in the values and they are not properties of the class. Inside the constructor, the base class constructor is called using super(). The firstname and lastname properties are then set using the standard “this” syntax.
The CustomerContact class has a single method GetContactDetails() that returns a custom JSON object. The JSON object has two members, viz. fullname and emailaddress.
Finally, add the following code at the end of the app.ts file:
var contact = new CustomerContact('Tom', 'Jerry', 'Company 1', 'USA'); contact.email = 'tom@somedomain.com'; var div = document.getElementById("div1"); div.innerHTML = contact.GetContactDetails().fullname + '<br>' + contact.GetContactDetails().emailaddress;
The above code creates an instance of CustomerContact class by passing various constructor parameters. It then gets hold of a <div> whose ID is div1 (you will create this HTML in a minute). It then sets the innerHTML of the <div> to the fullname and emailaddress members as returned by the GetContactDetails() method.
Build the project and open the app.js file. You will find that when you bind the project the TypeScript code is converted to equivalent JavaScript code as shown below:
var __extends = this.__extends || function (d, b) { function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var Customer = (function () { function Customer(company, country) { this.company = company; this.country = country; } return Customer; })(); var CustomerContact = (function (_super) { __extends(CustomerContact, _super); function CustomerContact(firstname, lastname, company, country) { _super.call(this, company, country); this.firstname = firstname; this.lastname = lastname; } CustomerContact.prototype.GetContactDetails = function () { var obj = { fullname: this.firstname + ' ' + this.lastname, emailaddress: this.email }; return obj; }; return CustomerContact; })(Customer); var contact = new CustomerContact('Tom', 'Jerry', 'Company 1', 'USA'); contact.email = 'tom@somedomain.com'; var div = document.getElementById("div1"); div.innerHTML = contact.GetContactDetails().fullname + '<br>' + contact.GetContactDetails().emailaddress; //@ sourceMappingURL=app.js.map
Now open the default HTML page from the project and key-in the following HTML markup into it:
<!DOCTYPE html> <html lang="en" > <head> <meta charset="utf-8" /> <title>TypeScript HTML App</title> <link rel="stylesheet" href="app.css" type="text/css" /> </head> <body> <h1>TypeScript HTML App</h1> <div id="div1"/> <script src="app.js"></script> </body> </html
Note that the HTML page refers the app.js file and not the app.ts file.
Run the HTML page in the browser and you should see something as shown below:
Run the HTML page in the browser
Notice how the <div> shows the CustomerContact property values.
Summary
TypeScript is a superset of JavaScript that provides typed nature to your code. Using TypeScript you can create classes and interfaces in your JavaScript code. More importantly TypeScript code, when compiled, gets converted into the same standard JavaScript. TypeScript not only makes the overall JavaScript usage easy it also makes your JavaScript code more structured and neat. Additionally, TypeScript, being an Open Source effort, offers all the benefits of an open source framework. More details about this new language can be read here.
About the Author:
Bipin Joshi is a blogger and author who writes about apparently unrelated topics – Yoga & technology! A former Software Consultant and Trainer by profession, Bipin is programming since 1995 and is working with .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. Having embraced Yoga way of life he now writes about Yoga, life and technology on his website. He can also be reached there.