Showing posts with label TypeScript. Show all posts
Showing posts with label TypeScript. Show all posts

Friday, 25 September 2015

Writing Gulpfile using TypeScript

Lately, I have been using Gulp a lot at my work and also in the demos of my articles. I also use TypeScript quite often these days while playing with Angular 2. While using Gulp to transpile TypeScript to JavaScript using Gulp, I got thought to use TypeScript itself to write the gulpfile as well. It might sound a bit weird as we use Gulp to transpile the files to JavaScript and the gulpfile itself has to be converted by someone into JavaScript before any other task runs. Thanks to npm scripts, we have a way to achieve this.

The scripts section of the package.json file can be used to register commands and these commands can be executed from command prompt of any OS using the “npm run” command. For instance, if we have the following configuration saved in scripts section of package.json file:

"scripts": {
  "setup" : "npm install && bower install"
}

We can run the command “npm run setup” from the command prompt. This command would install all Node.js dependencies and the bower dependencies. We can transpile the gulpfile using this section and then combine this command with a command to run a task. For this, we need to have TypeScript installed globally. This can be done using the following command:

> npm install –g typescript

To write the gulpfile using TypeScript and take advantage of the type checking system, we need to get the type definition files. Type definitions for the gulpfile are available on tsd. Following command gets the type definitions for the gulpfile:

> tsd install gulp --save

These files are saved inside typings folder of the project. To make our lives easier, the tsd command creates a type definition file that refers to all of the installed type definitions. This file is tsd.d.ts inside the typings folder.

Now, we need to refer the tsd.d.ts file in the gulpfile.ts file and start writing Gulp tasks. Following snippet shows a task that concatenates all JavaScript files:

/// <reference path="typings/tsd.d.ts" />

var gulp = require('gulp'),
    concat = require('gulp-concat');

gulp.task('default', function(){
  return gulp.src(["scripts/*.js"])
    .pipe(concat("combined.js"))
    .pipe(gulp.dest("dist"));
});

This example is a simple one. In more advanced scenarios, we can use types as well.

To run this gulp task, we need to define a command in the scripts section to transpile the file and then run the task. Following is the command:

"scripts": {
  "concat": "tsc gulpfile.ts && gulp"
}

All is done. We can now run this command as follows:

> npm run concat

Happy coding!

Sunday, 20 January 2013

Method overloading in TypeScript

TypeScript is observed as an object oriented language. Because of which we expect it to behave just like any other object oriented program out there. One of the key features of any object oriented language is method overloading. The way TypeScript supports this feature is a bit different.

In TypeScript, we cannot create multiple methods with same name in a class. If we attempt to do it, we get an error saying Duplicate identifier <Method name>. It happens even if the methods are defined by following all the rules of method overloading.

The way to achieve method overloading in TypeScript is we have to define a method with highest parameters and declare the other methods. Following sample demonstrates it:

class MyClass
{
 Display(num?: number,name?: string){
  document.write("x is: "+num.toString()+" and y is: "+name);
 }
 Display(num: number);
 Display(name: string);
 Display();
}

As we see, we have defined a Display method with two null able parameters and declared three Display methods with one or no parameters. This code compiles to following JavaScript:
var MyClass = (function () {
    function MyClass() { }
    MyClass.prototype.Display = function (num, name) {
        document.write("x is: " + num.toString() + " and y is: " + name);
    };
    return MyClass;
})();

Yes, there is just one function named Display. Because, a JavaScript function can be called passing all or less number of parameters. This applies to constructor as well.
class MyClass
{
 num: number;
 name: string;
 
 constructor(x?: number,str?: string){
  this.num=x;
  this.name=str;
 }
 constructor(x: number);
 constructor(str: string);
 constructor();
}

This compiles to:
var MyClass = (function () {
    function MyClass(x, str) {
        this.num = x;
        this.name = str;
    }
    return MyClass;
})();

It is important to note that the parameters that have to be omitted in overloads should be marked as nullable in the concrete method. Otherwise, the parameter becomes mandatory and TypeScript compiler reports an error.

Happy coding!

Wednesday, 10 October 2012

Creating TypeScript type declaration file for an existing jQuery plugin

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:
$(document).idleTimeout({
    inactivity: 5000,
    noconfirm: 1000,
    sessionAlive: 1000,
    redirect_url: 'TimedOut.html',
    click_reset: true,
    alive_url: 'default.htm',
    showDialog: false
});

The above script sets redirects user to the page TimedOut.html if the user didn’t interact with the page for 5 seconds or more.
From the usage of the plugin, it is clearly visible that,

  • The function idleTimeout is invoked using jQuery object
  • The function idleTimeout accepts a set of options
In the source of jQuery-idleTimeout plugin, we see the following assignment statement in the beginning:
var defaults = {
            inactivity: 1200000, //20 Minutes
            noconfirm: 10000, //10 Seconds
            sessionAlive: 30000, //10 Minutes
            redirect_url: '/js_sandbox/',
            click_reset: true,
            alive_url: '/js_sandbox/',
            logout_url: '/js_sandbox/',
            showDialog: true
        }

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 interface can be as follows:
interface JQIdleTimeoutSettings {
    inactivity?: number;
    noconfirm?: number;
    sessionAlive?: number;
    redirect_url?: string;
    click_reset?: bool;
    alive_url?: string;
    logout_url?: string;
    showDialog?: bool;
    }


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:
interface JQueryTimeout extends JQuery {
    idleTimeout(settings: JQIdleTimeoutSettings): JQueryTimeout;
}

I made the declaration file open on GitHub. You can find it here.

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.
/// <reference path="jQueryIdleTimeout.d.ts" />

(<JQueryTimeout>$(document)).idleTimeout({
                inactivity: 5000,
                noconfirm: 1000,
                sessionAlive: 1000,
                redirect_url: 'TimedOut.html',
                click_reset: true,
                alive_url: 'default.htm',
                showDialog: false
});
This is because, in TypeScript, $(document) returns an object of type JQuery. The function idleTimeout is declared in the interface JQueryTimeout, which is extended from the interface JQuery.

Happy coding!