TypeScript Arrow Function Tutorial

Update: New and better Boilerplate that uses ES6 Modules in TypeScript check it out.

So I’ve playing around with the TypeScript Arrow Function Expression. In this TypeScript tutorial I will show you a couple of examples using Arrow Functions.

Below you will see some normal JavaScript where we create an Image Object. We pass in an anonymous function to be called by the Image Object’s “onload” event but we also want to call another “onImageLoad” function within the same scope as the Image Object. To do this we create a variable called “self” to hold a reference to the Main class scope and pass it into the “onload” function so we can call “self.onImageLoad(event);”. Hope that makes sense. In the next example I will show you how to change the code to use TypeScript’s Arrow Function.

 
class Main {

    private _image:HTMLImageElement = null;

    constructor(path:string)
    {
        var self = this;
        this._image = new Image();
        this._image.onload = function(event) {
            self.onImageLoad(event);
        }
        this._image.src = path;
    }

    private onImageLoad(event):void
    {
        console.log("onImageLoad");
    }
}

If you look below we have removed the variable called self and now we are not passing in an anonymous function to the “onload” event. We are passing in (event) => {…} and that is the arrow => function. If there are no arguments being sent then the Arrow function would look like () => {…}. Now notice that we are calling “this.onImageLoad(event);” with a this and not a self. That’s about it.

 
class Main {

    private _image:HTMLImageElement = null;

    constructor(path:string)
    {
        this._image = new Image();
        this._image.onload = (event) => {
            this.onImageLoad(event);
        }
        this._image.src = path;
    }

    private onImageLoad(event):void
    {
        console.log("onImageLoad");
    }
}

“Arrow function expressions are a compact form of function expressions that omit the function keyword and have lexical scoping of this.” Basically the Arrow Function helps you retain a certain scope automatically. If you look at the outputted code from the compiler, it just creates a var _this = this; and it is used inside the function.

Below is what the Arrow Function will be compiled out to. Notice the var _this = this.

 
var Main = (function () {
    function Main(path) {
        var _this = this;
        this._image = null;
        this._image = new Image();
        this._image.onload = function (event) {
            _this.onImageLoad(event);
        };
        this._image.src = path;
    }
    Main.prototype.onImageLoad = function (event) {
        console.log("onImageLoad");
    };
    return Main;
})();

jQuery and TypeScript Arrow Functions

On to the second example. Not sure if we need another one but I wrote this code as the original example.

First thing is we need to bring in our jQuery declaration (jquery-1.8.d.ts) file. The below example is a common way to setup a jQuery object with click handlers. We have an anonymous funciton with some sample code inside. With larger project I do not like doing it this way because the code becomes hard to read and manage.

 
///<reference path='_declare/jquery-1.8.d.ts'/>

class Main {

    private TIME_TEXT:string = "Timer is complete.";//Constant

    constructor()
    {
        var self = this;
        $(".js-alert-link").on("click", function(event){
            var referenceToATag = this;
            var $referenceToATag = $(this);

            setTimeout(function() {
                self.timerComplete();
            }, 100);
        });
    }

    private timerComplete():void
    {
        alert(this.TIME_TEXT);
    }

}

Typically what I like to do is create a function within the class and bind the function call. Hope you see the difference.

 
///<reference path='_declare/jquery-1.8.d.ts'/>

class Main {

    private TIME_TEXT:string = "Timer is complete.";//Constant

    constructor()
    {
        $(".js-alert-link").on("click", this.startTimer.bind(this));
    }

    public startTimer(event):void
    {
        var referenceToATag = event.target;
        var $referenceToATag = $(event.target);

        var self = this;
        setTimeout(function() {
            self.timerComplete();
        }, 100);
    }

    private timerComplete():void
    {
        alert(this.TIME_TEXT);
    }

}

Taking a look at the below example and the previous one. We will convert some of the code to use TypeScript’s Arrow Functions. Take a look at (event) => this.startTimer(event) and compare it with the above. Also we converted the “setTimeout” call to use the Arrow Function. There are no arguments sent so this Arrow Funciton looks like () => { this.timerComplete(); }

 
///<reference path='_declare/jquery-1.8.d.ts'/>

class Main {

    private TIME_TEXT:string = "Timer is complete.";//Constant

    constructor()
    {
        $(".js-alert-link").on("click", (event) => this.startTimer(event));
    }

    public startTimer(event):void
    {
        var referenceToATag = event.target;
        var $referenceToATag = $(event.target);

        setTimeout(() => {
            this.timerComplete();
        }, 100);
    }

    private timerComplete():void
    {
        alert(this.TIME_TEXT);
    }

}

Taking the same code above we will add the appropriate typing for some of the parameters and variables. Check it out, we added a JQueryEventObject, HTMLAnchorElement and JQuery type.
We also need to do some type casting because the compiler doesn’t know that the event.target is an HTMLAnchorElement. To cast something we place the type inside a less than and greater than symbol and place it before the object like:

 
<HTMLAnchorElement> event.target

Why add all these types to objects and variables? It make your life easier when you have an IDE the supports code completion and refactoring. The next version of WebStorm and PhpStorm have support for TypeScript. So does Visual Studio but I am not a .Net guy just yet.

 
///<reference path='_declare/jquery-1.8.d.ts'/>

class Main {

    private TIME_TEXT:string = "Timer is complete.";//Constant

    constructor()
    {
        $(".js-alert-link").on("click", (event:JQueryEventObject) => this.startTimer(event));
    }

    public startTimer(event:JQueryEventObject):void
    {
        var referenceToATag:HTMLAnchorElement = <HTMLAnchorElement> event.target;
        var $referenceToATag:JQuery = $(event.target);

        setTimeout(() => {
            this.timerComplete();
        }, 100);
    }

    private timerComplete():void
    {
        alert(this.TIME_TEXT);
    }

}

Below you can download the TypeScript tutorial example files. Also if you like this tutorial please provide a link back to this page or my site.

5 Responses to “TypeScript Arrow Function Tutorial”

  1. Nice feature if be honest, thanks

  2. This is what I was looking for! Thanks for these articles!

  3. Wow, a totally awesum tutorial! And I like your way of writing. You seem to be a nice guy, in this game for the fun of it and one likes to share your knowledge. I’m totally sold on TypeScript since yesterday when I began reading about it. Really makes a JavaScritper’s life so much easier. The sad thing though is that Visual Studio 2012 does not support TypeScript in the class view window. So all we have in the IDE is our code and the IntelliSense feature. But I figure that will come to in the future.

  4. Thank you so much! It was very frustrating getting the correct scope to get to my variables. Even though I saw some answers at stackoverflow your examples are what finally made me get it to work.

    As a C# developer I thought that going with Typescript would be easier than just using javascript. So far it doesn’t really feel that way. Will see though.

Leave a Reply