Joshua Frank
Joshua Frank

Reputation: 13838

How can I get TypeScript to work with jQuery Plugins?

I've got a jQuery plugin that works in the standard way:

$.fn.doSomething = function () {
//do something to each item in the list
}

In regular javascript, I can then invoke doSomething as if it were really part of jQuery:

$(selector).doSomething();

Typescript using the jquery.d.ts reference works fine with jQuery, but doesn't know anything about my plugin, and so I get:

The property 'doSomething' does not exist on value of type 'JQuery'.

So how do I tell TypeScript about the additional functionality that I added?

Upvotes: 1

Views: 242

Answers (1)

Kyle
Kyle

Reputation: 33701

You need a typings definition file for the plugin.

Some common libraries are available here(and through nuget) https://github.com/borisyankov/DefinitelyTyped

You may want to search google to see if yours is already made by someone. If not, you just need to make your own.

For example, if I wanted to be able to do $('#idOfElement').autosize();

I would create a .d.ts file containing this code:

interface JQuery {
    autosize(): JQuery;
}

Or maybe auto size takes some options, in which case you could define it like this:

interface JQuery {
    autosize(): JQuery;
    autosize(options: autosizeOptions): JQuery;
}

interface autosizeOptions {
    className?: string;
    append?: string;
    callback?: any;
}

Upvotes: 3

Related Questions