How to Extend the jQuery Interface with Additional Methods in TypeScript

It is surprisingly simple. At first I tried it with methods like jQuery.fn.extends, but that did not bear fruit. Then I played around with the TypeScript keywords extends and implements, but there too I always ran into some errors.

Only then did it occur to me to look at existing .d.ts files to see how they do it – and I was very surprised. To extend an interface with new methods, all you need to do is create an interface with the same name. So I created a file jquery.tagcloud.d.ts (analogous to jquery.tagcloud.js, where these methods are implemented) and wrote the following into it:

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

interface JQuery
{
tagcloud(): void;
//-It has to be of type any because I pass parameters to this method in curly braces
tagsInput(args: any): void;
}

I then call these methods like this:

JS
$('#tags').tagsInput({ width: "auto" });
$('#tagCloud a').tagcloud();

And that is all there is to it. I will just add that, in the same way, you can extend $ with static methods by creating an interface named JQueryStatic and adding the methods to it, but I have not tried that. From now on, all the errors are gone that Visual Studio was reporting to me regarding TypeScript.

Categories

Leave a Reply