【问题标题】:How to use added typings in typescript如何在打字稿中使用添加的类型
【发布时间】:2017-02-26 14:01:31
【问题描述】:

我正在尝试学习 Typescript,并按照this 教程建立了一个基本的 typescript 结构。

我现在需要在项目中添加类型。于是我环顾四周,发现typings。然后我使用类型添加了JQueryLodashD3。我的项目结构如下所示:

├── dist
│   ├── chart.js
│   ├── greet.js
│   └── main.js
├── gulpfile.js
├── package.json
├── src
│   └── ts
│       ├── chart.ts
│       ├── greet.ts
│       └── main.ts
├── tsconfig.json
├── typings
│   ├── globals
│   │   └── jquery
│   │       ├── index.d.ts
│   │       └── typings.json
│   ├── index.d.ts
│   └── modules
│       ├── d3
│       │   ├── index.d.ts
│       │   └── typings.json
│       └── lodash
│           ├── index.d.ts
│           └── typings.json
└── typings.json

这是我的tsconfig.json 文件:

{
    "files": [
        "src/ts/*.ts"
    ],
    "compilerOptions": {
        "noImplicitAny": true,
        "target": "es5"
    }
}

我的问题是,如何在我的main.ts 文件中添加我在typings 目录中的*.d.ts 文件并开始使用jQuery 的$ 或D3 的d3

我注意到typings 中的index.d.ts 文件看起来像这样:

/// <reference path="globals/jquery/index.d.ts" />
/// <reference path="modules/d3/index.d.ts" />
/// <reference path="modules/lodash/index.d.ts" />

所以我的猜测是,我只需将此文件添加到我的 main.ts 文件或 tsconfig.json 文件中的某个位置(而不是手动添加每个 .d.ts 文件)。我对吗?谢谢。

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    您可以将其添加到您的 tsconfig 中:

    "files": [
        "src/ts/*.ts",
        "typings/**/*.ts"
    ]
    

    或者只是

    "files": [
        "src/ts/*.ts",
        "typings/index.d.ts"
    ]
    

    【讨论】:

    • 谢谢 Alex,我已在我的 tssconfig.json 中添加了 index.d.ts 文件。现在如何让我的.ts 文件识别$ 和此类符号?我是否必须在我的 .ts 文件中添加/要求任何内容?
    • 我添加了import $ from "./jquery";,也尝试了import $ from "jquery";,但出现以下错误:cannot fine module jquery
    【解决方案2】:

    TypeScript 2 建议对类型使用 npm。见The Future of Declaration Files

    你只需要这样的东西:

    npm install --save @types/lodash @types/d3 @types/jquery
    

    一切顺利。

    【讨论】:

    • 您不希望它们成为开发依赖项。使用 save 而不是 save-dev 使它们成为依赖项。
    • @randominstanceOfLivingThing 好的,我将其修改为 --save ,如文章中所述。您也许可以回答我创建的关于为什么需要这样做的问题。谢谢。 stackoverflow.com/questions/40097488/…
    • 我怀疑在 typescripts 编译成js 之后使用@types。所以我敢打赌,没有必要让他们作为生产部门。
    • @user61382 从我的后续问题的回答中,“当您可能有依赖项时,问题就会出现。如果您将类型声明存储在您的 devDependencies 中,您的消费者将不会自动获取您的类型声明。 ",这不是必需的,但对消费者有用。
    • @user61382 请在此处查看来自 TypeScript 成员的原始引用:github.com/Microsoft/types-publisher/issues/…
    猜你喜欢
    • 2021-08-06
    • 2018-04-23
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 2020-05-11
    相关资源
    最近更新 更多