Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot invoke an expression whose type lacks a call signature" when importing jQuery in TypeScript

I'm currently evaluating TypeScript and have some problems when trying to import jQuery.

import * as $ from 'jquery';
const $el = $('#app');

report the following error:

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.

I have installed the jQuery module as follows:

npm i jquery --save
npm i @types/jquery --save-dev

and use the following generated tsconfig.json file:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true
  }
}

I'm using the following versions:

{
  "name": "example",
  "version": "1.0.0",
  "description": "example",
  "devDependencies": {
    "@types/jquery": "3.3.22",
    "typescript": "3.1.6",
  },
  "dependencies": {
    "jquery": "3.3.1"
  }
}

What am I missing?

like image 541
doberkofler Avatar asked Nov 27 '18 07:11

doberkofler


2 Answers

As @types/jquery uses export =, importing it requires using import =.

Change

import * as $ from 'jquery';

to

import $ = require('jquery');
like image 172
Leonard Thieu Avatar answered Nov 18 '22 19:11

Leonard Thieu


For "module": "esnext", below may help,

import jQuery from "jquery";
window.$ = window.jQuery = jQuery;
like image 26
Haryono Avatar answered Nov 18 '22 18:11

Haryono