In my package.json
file, I have the following dependencies defined:
{
"dependencies": {
"@types/jquery": "^3.5.5",
}
}
This adds type declarations through @types/jquery/misc.d.ts
, including:
declare const jQuery: JQueryStatic;
declare const $: JQueryStatic;
However, having global variables like $
and jQuery
defined for all modules is causing issues in my code. TypeScript compiler assumes that $
is a global variable when it should be imported specifically for each module, leading to runtime errors like:
// $ is never imported here, and jQuery is not initialized globally in the browser
export function foo(node?:JQueryXML):void {
node.children().each(function(_, el) {
let node = $(el);
if (node.attr("type") === VALUE) {
doStuff();
}
});
}
When I commented out the declaration lines in @types/jquery/misc.d.ts
, I received an error as expected:
error TS2592: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig.
40 let node = $(el);
Disabling those declarations created more than 50 errors because other modules where I import $
started treating it as any
. How can I inform the TypeScript compiler that I want the jQuery type definitions without having $
as a global variable?