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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With