使用 Typescript 时如何停止“类型 JQuery 上不存在属性”语法错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24984014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:43:45  来源:igfitidea点击:

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

jquerytypescript

提问by Alan2

I am only using one line of jQuery in my application:

我在我的应用程序中只使用了一行 jQuery:

$("div.printArea").printArea();

But this is giving me a Typescript error:

但这给了我一个打字稿错误:

The property 'printArea' does not exist on type JQuery?

JQuery 类型上不存在属性“printArea”?

Can someone tell me how I can stop this error appearing?

有人可以告诉我如何停止出现此错误吗?

回答by PSL

You could cast it to <any>or extend the jquery typing to add your own method.

您可以将其转换为<any>或扩展 jquery 类型以添加​​您自己的方法。

 (<any>$("div.printArea")).printArea();

//Or add your own custom methods (Assuming this is added by yourself as a part of custom plugin)

//或者添加你自己的自定义方法(假设这是你自己添加的作为自定义插件的一部分)

interface JQuery {
    printArea():void;
}

回答by Eldamir

I think this is the most readable solution:

我认为这是最易读的解决方案:

($("div.printArea") as any).printArea();

回答by vishnu

You can cast it to

你可以将它投射到

(<any>$('.selector') ).function();

Ex: date picker initialize using jquery

例如:日期选择器使用 jquery 初始化

(<any>$('.datepicker') ).datepicker();

回答by AlexB

For your example, you'd add this:

对于您的示例,您将添加以下内容:

interface JQuery{
    printArea():void;
}

Edit: oops, basarat is correct below. I'm not sure why I thought it was compiling but I've updated this answer.

编辑:哎呀,basarat 在下面是正确的。我不确定为什么我认为它正在编译,但我已经更新了这个答案。

回答by Albin Sunnanbo

Since printArea is a jQuery plugin it is not included in jquery.d.ts.

因为printArea 是一个jQuery 插件,所以它不包含在jquery.d.ts 中。

You need to create a jquery.printArea.ts definition file.

您需要创建一个 jquery.printArea.ts 定义文件。

If you create a complete definition file for the plugin you may want to submit it to DefinitelyTyped.

如果您为插件创建了一个完整的定义文件,您可能希望将其提交给绝对类型

回答by iqqmuT

You can also write it like this:

你也可以这样写:

let elem: any;
elem = $("div.printArea");
elem.printArea();