Annotating legacy jQuery plugins with Typescript
Annotating legacy jQuery with Typescript can be a pain. Many old plugins don’t have type definitions available, and the official types only get you so far on their own.
Instead of littering your code base with separate .d.ts
definition files, it can be very convenient to annotate the types inline in the component file itself.
The following examples cover most common use cases:
type PluginInstance = JQuery & {
// Any methods or properties the plugin adds, e.g. `jQuery(selector).plugin().instanceMethod()`
instanceMethod: () => any;
};
type StaticProperties = {
// Any static methods or properties the plugin adds, e.g. `jQuery.fn.plugin.staticProperty`
staticProperty: any;
};
type Plugin = ((...args: any[]) => PluginInstance) & StaticProperties;
declare global {
interface JQuery {
plugin: Plugin;
}
}
The following code snippets will then make sense for Typescript:
const globalConfig = {};
jQuery.fn.plugin.staticProperty = globalConfig;
const instance = jQuery(selector).plugin();
const result = instance.instanceMethod();