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

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

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

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

类型 JQuery 上不存在属性‘ printArea’?

谁能告诉我怎样才能阻止这个错误出现?

130945 次浏览

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

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

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

declare global {
interface JQuery {
printArea(): void;
}
}

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

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

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

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.

I think this is the most readable solution:

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

You can cast it to

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

Ex: date picker initialize using jquery

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

You can also write it like this:

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

You can also use the ignore syntax instead of using (or better the 'as any') notation:

// @ts-ignore
$("div.printArea").printArea();