Pages

Wednesday, 10 October 2012

Microsoft recently announced a scripting language that compiles into JavaScript. It is known as TypeScript.
TypeScript is super set of JavaScript. Using TypeScript, one can write type safe client side script. If you are not familiar with TypeScript yet, you may checkout the following resources:

Any existing JavaScript library can be used with TypeScript if a type declaration file is created for the library. A type declaration file provides a TypeScript interface to interact with the library. TypeScript team has created the declaration files for jQuery and Node.js libraries.
In this post, we will create a TypeScript declaration file for jQuery-idle Timeout plugin. It is a small plugin which signs off the user if the user didn’t interact with the page for some time. Using this plugin is very easy. Following is an example of the usage:

From here, we get to know the list of configurable options.
As TypeScript is strongly typed, we need to define an interface to hold the
above properties. One important thing to
remember here is that, the fields should be made nullable in the interface.

The function idleTimeout is invoked using a jQuery
object. In the declaration file of jQuery, an interface is defined to hold all
functions which have to be invoked using jQuery objects. Name of the interface
is JQuery.

We shouldn’t modify the source of jQuery’s declaration file to add the idleTimeout function. Instead, we have to define an interface extending JQuery as follows:

Using the declaration file:
To use the declaration file in a TypeScript file, a reference of the declaration file should be added. Calling the idleTimeout function in TypeScript is quite similar to that of in JavaScript code. Only difference being, we need to type cast the jQuery object to type of JQueryTimeout.

5 comments:

Ravi, Great post! I tried this and wrote a declaration file for some library. I believe it is fine now but I think when it gets larger it will be prune to mistakes. How can I check the syntax of the mydeclarations.d.ts file?

Ignacio,Glad that you found it useful.You might be using the word interface to name a variable or function. Interface is a keyword in TypeScript. If you are using VS, I recommend you to install Web Essentials. It makes writing TypeScript very easy on VS.

About Me

I am a software developer working on and passionate about Microsoft Technologies and anything new in the Web world. Lately, spending a lot of time with JavaScript and finding it much deeper than what I knew for past few years. I enjoy writing code and writing about code. My contribution to community earned me a Microsoft MVP award (ASP.NET/IIS) and a DZone MVB award. When not in front of computers, like to spend time with melodious Hindi and Telugu tunes or watching Cricket