5

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You're right, that was the problem. It seems very non-obvious but it does make sense. Thanks!
@curpa I also have a similar question. Wanted to see if you can help me.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.