"Kan inte anropa ett uttryck vars typ saknar en anropssignatur" när man importerar jQuery i TypeScript
Jag utvärderar för närvarande TypeScript och har några problem när jag försöker importera jQuery.
import * as $ from 'jquery';
const $el = $('#app');
rapportera följande fel:
src/log.ts:2:13 - error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '{ default: JQueryStatic; ajaxSettings: AjaxSettings<any>; A
nimation: AnimationStatic; Callbacks: CallbacksStatic; cssHooks: CSSHooks; cssNumber: PlainObject<boolean>; Deferred: DeferredStatic; ... 62 more ...; when<TR1,
UR1, VR1, TJ1 = any, UJ1 = any, VJ1 = any>(deferredT: TR1 | ... 1 more ... | Thenable<...>, defer...' has no compatible call signatures.
2 const $el = $('#app');
~~~~~~~~~
src/log.ts:1:1
1 import * as $ from 'jquery';
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default impo
rt or import require here instead.
Jag har installerat jQuery-modulen på följande sätt:
npm i jquery --save
npm i @types/jquery --save-dev
och använd den följande genererade tsconfig.json-filen:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true
}
}
Jag använder följande versioner:
{
"name": "example",
"version": "1.0.0",
"description": "example",
"devDependencies": {
"@types/jquery": "3.3.22",
"typescript": "3.1.6",
},
"dependencies": {
"jquery": "3.3.1"
}
}
Vad missar jag?
Svar #1
Eftersom @types/jquery använder export =, kräver importering av det att man använder import =.
Ändra
import * as $ from 'jquery';
till
import $ = require('jquery');
Svar #2
För "module": "esnext", nedan kan hjälpa,
import jQuery from "jquery";
window.$ = window.jQuery = jQuery;
