如何在打字稿中使用添加的打字

How to use added typings in typescript

我正在尝试学习 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"
    }
}

我的问题是,如何将 typings 目录中的 *.d.ts 文件添加到我的 main.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 文件)。我对吗?谢谢。

您可以在您的 tsconfig 中添加它:

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

或者只是

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

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

你只需要这样的东西:

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

一切顺利。