Wednesday, 23 January 2013

Simple Visual Studio TypeScript HTML App with jQuery

I heard about TypeScript a few months ago and have had a bit of a play-around compiling some TypeScript into JavaScript using the Node.js package, but I've not had chance to try it out in Visual Studio. Here is a simple demo that shows how the code generated by the TypeScript project template can be adapted to include jQuery support.

Thanks to this stackoverflow answer for getting me started.

Step 1: Install TypeScript Plugin

Install the Visual Studio 2012 TypeScript plugin from here

Step 2: Create a Project

Create a new project in Visual Studio 2012 using the HTML Application with TypeScript project template

Step 3: Include the jQuery Type Definitions

Create a new file in the project and call it jquery.d.ts

Paste in the type definitions from from here

Step 4: Update the app.ts File

Change the code in the app.ts file to...

/// <reference path="jquery.d.ts" />

class Greeter {
    element: JQuery;
    span: JQuery;
    timerToken: number;
    
    constructor(element: JQuery) {

        this.element = element;
        this.element.text("The time is: ");
        this.span = $('<span>');
        this.element.append(this.span);
        this.span.text(new Date().toUTCString());
    }

    start() {
        this.timerToken = setInterval(() => {
            this.span.text(new Date().toUTCString());
        }, 500);
    }

    stop() {
        clearTimeout(this.timerToken);
    }

}

$(() => {
    var el = $("#content");
    var greeter = new Greeter(el);
    greeter.start();
});

Step 5: Include Reference to jQuery Library

Add the following markup to the head section of the default.htm file...

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

Step 6: Run or Debug

Run or Debug the application to see the TypeScript in action.

You can even put breakpoints in the app.ts file.