简体   繁体   中英

In TypeScript, how do I extend the ambient JQuery interface in an external module?

I'm creating jQuery plugins using external modules in TypeScript. It seems as that if I add the interfaces directly to the modules I cannot add the new methods to the JQuery ambient interface declaration.

Eg in jquery.d.ts

declare interface JQuery {
    ...
    text(): string;

    text(text: string|number|boolean): JQuery;
    ...
}

I have an external module that adds a JQuery plugin and extends the JQuery interface, but other modules that import that module don't seem to see it. I'm guessing that it doesn't mix since the declaration just overrides the ambient JQuery interface declaration rather than extend it.

It looks something like (in myplugin.ts):

interface MyCoolOptions {
    text?: string;
}

interface JQuery {
    myCoolPlugin(options: MyCoolOptions): JQuery;
}

$.fn.myCoolPlugin = function(options: MyCoolOptions) { this.text(option.text); }

I then import the plugin in another file before I use it.

import * as cool from "myplugin";

$(".selector").myCoolPlugin({ text: "cool" });

The problem is that I'm getting a message saying "Property 'myCoolPlugin' does not exist on type JQuery". I'd rather not have to duplicate the interfaces in an ambient declaration. Is there a way to extend the JQuery interface without having to redefine the MyCoolOptions interface in type definition file ( .d.ts )?

It seems as that if I add the interfaces directly to the modules I cannot add the new methods to the JQuery ambient interface declaration.

Yes you need to have yourlib.d.ts to specify how you have extended the global JQuery and then a yourlib.ts that can use external modules .

Alternatively you can just write your code in a global manner .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM