[英]In TypeScript, how do I extend the ambient JQuery interface in an external module?
I'm creating jQuery plugins using external modules in TypeScript. 我正在使用TypeScript中的外部模块创建jQuery插件。 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.
看来,如果我直接将接口添加到模块中,则无法将新方法添加到JQuery环境接口声明中。
Eg in jquery.d.ts
例如在
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. 我有一个外部模块,该模块添加了一个JQuery插件并扩展了JQuery接口,但是导入该模块的其他模块似乎看不到它。 I'm guessing that it doesn't mix since the declaration just overrides the ambient JQuery interface declaration rather than extend it.
我猜它不会混合,因为声明只是覆盖环境JQuery接口声明而不是扩展它。
It looks something like (in myplugin.ts): 看起来像(在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". 问题是我收到一条消息,指出“ JQuery类型上不存在属性'myCoolPlugin'”。 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
)? 有没有一种方法可以扩展JQuery接口,而不必在类型定义文件(
.d.ts
)中重新定义MyCoolOptions接口?
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.
看来,如果我直接将接口添加到模块中,则无法将新方法添加到JQuery环境接口声明中。
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 . 是的,您需要具有
yourlib.d.ts
来指定如何扩展全局JQuery
,然后yourlib.ts
可以使用外部模块的yourlib.ts
。
Alternatively you can just write your code in a global manner . 或者,您可以仅以全局方式编写代码 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.