typescript 导入 jquery 后,打字稿找不到名称“$”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28815866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:57:58  来源:igfitidea点击:

Typescript cannot find name '$' after importing jquery?

jquerytypescript

提问by Smartboy

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

我正在使用 TypeScript 1.4.1,并且有一个如下所示的项目:

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:

我的 main/test.ts 包含以下内容:

/// <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?

我的问题是:鉴于上述内容不起作用,我该如何引用 jquery?或者,我只是做错了什么?

采纳答案by curpa

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

更改($el: $.JQuery)($el: JQuery)

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

$是一个变量,所以它不能用在类型注释中。JQuery是一个接口,所以它可以用在类型注解中。

回答by user10318357

just install jquery library

只需安装 jquery 库

yarn add @types/jquery --save

typescript will automatically import this library.

typescript 会自动导入这个库。

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

如果你想用 npm 而不是 yarn 安装,代码应该是这样的

npm install --save @types/jquery