Veit's Blog

Hej! đź‘‹ Welcome to my curated space of insights on software development and the tapestry of life.

TypeScript and jQuery

2015-07-31

If you want to use an existing JavaScript library with TypeScript you need some kind of header file. This file, called definition file, contains type informations about the JavaScript library and enables the TypeScript developer to use the library objects like they where TypeScript objects. You can either write your own (I will write a blog post about that in the near future) or take advantage of TSD, a manager for TypeScript definition files based on the GitHub repository Definitely Typed. Definitely Typed is community driven library for nearly 1000 TypeScript definition files.

At first you have to install TSD with npm.

$ npm install tsd -g

Now change to your TypeScript project folder and initialize TSD. With init TSD creates two files: tsd.json and typings/tsd.d.ts. The tsd.d.ts is a TypeScript definition file which refers to all libraries that where installed with TSD. So you just have to refer to a single file instead to multiple files.

$ tsd init

So it’s time to install jQuery (or any other library) with the install command.

$ tsd install jquery --save

Now you’re able to use jQuery in your TypeScript code. Note the first line which is important to include the TSD definition file. It’s not just a comment!

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

class Person {
    private _firstname:string;
    private _lastname:string;


    constructor(firstname:string, lastname:string) {
        this._firstname = firstname;
        this._lastname = lastname;
    }

    public getName():string {
        return this._lastname + ", " + this._firstname;
    }
}

$(document).ready(function () {
    var person1:Person = new Person("Jasper", "Beardly");
    var message = person1.getName();

    $("#status")[0].innerHTML = message;
});