Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript cannot find name '$' after importing jquery?

I am using TypeScript 1.4.1, and have a project laid out like so:

scripts/
    libs/
        jquery/
            jquery.d.ts // Latest from DefinitelyTyped
            jquery.js // 2.1.3
        lodash/
            lodash.d.ts // Latest from DefinitelyTyped
            lodash.js // 3.3.1
    main/
        test.ts

My main/test.ts contains the following:

/// <reference path="../libs/lodash/lodash.d.ts" />
/// <reference path="../libs/jquery/jquery.d.ts" />

import _ = require("lodash");
import $ = require("jquery");

function requireExistingElement($el: $.JQuery) {
    if(_.isUndefined($el) || _.isNull($el) || $el.length === 0) {
        throw new Error("It appears the requested element does not exist?");
    }
}

requireExistingElement($("body"));

This is compiled with the following command:

tsc --module amd scripts/main/test.ts

I expect this to run correctly, but when I compile it I get:

scripts/main/test.ts(7,38): error TS2304: Cannot find name '$'.
scripts/main/test.ts(13,24): error TS2304: Cannot find name '$'.

My question is: How do I reference jquery given that the above is not working? Or, am I just doing something wrong?

like image 480
Smartboy Avatar asked Mar 02 '15 17:03

Smartboy


2 Answers

change ($el: $.JQuery) to ($el: JQuery)

$ is a variable, so it can't be used in a type annotation. JQuery is an interface, so it can be used in a type annotation.

like image 195
curpa Avatar answered Nov 19 '22 20:11

curpa


just install jquery library

yarn add @types/jquery --save

typescript will automatically import this library.

if you want to install with npm instead of yarn, code should be as like

npm install --save @types/jquery
like image 1
user10318357 Avatar answered Nov 19 '22 18:11

user10318357