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

JqueryTypescript

Jquery Problem Overview


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

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

But this is giving me a Typescript error:

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

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

Jquery Solutions


Solution 1 - Jquery

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;
    }
}

Solution 2 - Jquery

I think this is the most readable solution:

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

Solution 3 - Jquery

You can cast it to

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

Ex: date picker initialize using jquery

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

Solution 4 - Jquery

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

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

Solution 5 - Jquery

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.

Solution 6 - Jquery

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.

Solution 7 - Jquery

You can also write it like this:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlan2View Question on Stackoverflow
Solution 1 - JqueryPSLView Answer on Stackoverflow
Solution 2 - JqueryEldamirView Answer on Stackoverflow
Solution 3 - JqueryvishnuView Answer on Stackoverflow
Solution 4 - JqueryGuntramView Answer on Stackoverflow
Solution 5 - JqueryAlexBView Answer on Stackoverflow
Solution 6 - JqueryAlbin SunnanboView Answer on Stackoverflow
Solution 7 - JqueryiqqmuTView Answer on Stackoverflow