Creating simple TypeScript “any” wrappers for jQuery plugin libraries

Posted: (EET/GMT+2)

 

Are you already using TypeScript? I'm myself using it in almost all new ASP.NET projects, and although there are still corners that could take some polishing, I'm very happy to move my existing JavaScript code into TypeScript.

Now, in TypeScript development, I often find myself in building simple declaration files (.d.ts files) for various jQuery plugins, and just today I needed to work with a nice component called qTip2.

This qTip component extends jQuery by defining a function called "qtip", but if you try to refer to this function from your otherwise well working TypeScript file (.ts), you end up getting the error message "Build: The property 'qtip' does not exist on value of type 'JQuery'."

The solution to this problem is to find (or create) a new declaration file so that the TypeScript compiler knows about this new function. Let's take an example. Say, you wanted to initialize qTip popups from your TypeScript file. You might have a function called initPopups for instance:

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

function initPopups(): void {
    alert("Hello from TypeScript!");
    $("#myButton").qtip();
}

If you try to build your project with this kind of code in place, it will fail with the above error message. However, if you add a new declaration file into your project and name it for instance "qtip.d.ts", the TypeScript compiler will find the declaration file, and then allow the code to build.

What should the "qtip.d.ts" file look like then? The easiest way to handle the situation – in case you are not really interested in supporting the full power of type declaration files and type checking TypeScript offers – you can simply use the "any" variable type like this:

interface JQuery {
    qtip(options?: any);
}

This will allow the TypeScript compiler to pass, but you won't get any checks on whether the parameters you've passed in to the qTip component really are valid. But, if you are just using these kind of plugins here and there, it probably doesn't matter.

Finally, a quick Visual Studio tip: to quickly insert the reference to a type declaration file into your .ts file, simply drag and drop a .d.ts file from Solution Explorer into your .ts file. This will add the reference like this:

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

Hope this helps!