【问题标题】:TS-2304 Error - can not find name 'Iterable' in TypeScript while importing "jquery" in ".ts" fileTS-2304 错误 - 在“.ts”文件中导入“jquery”时在 TypeScript 中找不到名称“Iterable”
【发布时间】:2018-01-04 11:32:56
【问题描述】:

我正在使用 Visual Studio Code 作为编辑器来开发 TypeScript 2.4 版。我使用以下命令安装了带有 NPM 的 jQuery:

npm install --save @types/jquery

然后我从GitHub下载了jquery module的源代码。

registrationpage.ts文件的代码如下:

import * as $ from 'jquery';
class Registration_Page {
    txtuname: string;
    Registration() {
        $('#table').hide;
        this.txtuname = ( <HTMLTextAreaElement> (document.getElementById('txtusername'))).value;
    }
}
window.onload = () => {
    $('#table').show;
    var bttnLogin = document.getElementById('submit');
    var obj = new Registration_Page();
    bttnLogin.onclick = function () {
        obj.Registration();
    }
}

index.html的代码如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="registrationpage.js"></script>

</head>
<body>
    <form id="form1">
    <div>
     <fieldset style="font-size: medium; color: #000000;">
        <legend style="background-color:#CCCCFF; font-size: larger;font-weight:bold">Registration Page in TypeScript</legend>
        <br />
        <b>UserName</b>
        <input id="txtusername" type="text" /><br />
        <br />

        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <input id="submit" type="button" value="Submit" />&nbsp;&nbsp;&nbsp;&nbsp;

    </fieldset>
    </div>
    <div id="table">
        <table>
            <tr>
                <th>UserName</th>

            </tr>
        </table>
    </div>
    </form>
</body>
</html>

tsconfig.json 文件:

{
    "compilerOptions": {
        "target": "es5",
        "noImplicitAny": true,
        "lib": [ "es2015", "dom" ]

    }

}

当我在 CMD 上编译代码时,出现以下错误:

错误 TS2304:找不到名称 Iterable

请提出适当的解决方案。

【问题讨论】:

  • 你找到解决办法了吗,我也有同样的问题
  • 我在 VS 2017 UI 中遇到了同样的问题。从你下面的回答听起来好像 tsconfig.json 被忽略了?你能提供更多细节吗?如何解决这个问题?
  • 是的,它忽略了 tsconfig.json 文件。解决方案是使用命令编译代码:“tsc -p”。请参考:“typescriptlang.org/docs/handbook/tsconfig-json.html

标签: jquery node.js typescript npm


【解决方案1】:

tsconfig.json的配置是正确的。当目标设置为 ES5 并且库 : es2015,es2015-iterable 包括在内时,则支持 Iterable。 关键是当我们通过命令tsc "filename" 编译.ts 文件时,编译器会忽略“tsconfig.json”。此外,在使用外部模块时,您需要包含以下js 文件以支持模块加载:

https://unpkg.com/core-js/client/shim.min.js">

https://unpkg.com/systemjs@0.19.39/dist/system.src.js

最后,用这个命令编译文件

**tsc -p .**

此命令不会忽略tsconfig.json 文件。

希望对您有所帮助。

【讨论】:

  • 这应该是公认的答案。没有人提到tsc 命令默认忽略tsconfig.json。谢谢!
【解决方案2】:

考虑安装节点类型定义。

npm i --save-dev @types/node

如果您使用 Yarn 而不是 NPM

yarn add -D @types/node

【讨论】:

  • 节点类型文件定义了 Iterable 以便在第 61 行附近与 --lib es5 一起使用。请参阅 node_modules/@ types/node/index.d.ts
猜你喜欢
  • 2019-07-13
  • 1970-01-01
  • 2020-06-24
  • 2019-12-25
  • 1970-01-01
  • 2019-08-14
  • 2021-01-27
  • 2016-06-23
  • 2018-07-08
相关资源
最近更新 更多