How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?
JqueryTypescriptJquery 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
// @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();