如何在打字稿 2.0 / 3.0 中添加自定义 "typings"

How to add custom "typings" in typescript 2.0 / 3.0

根据 this 文章,打字稿 2.0 的打字系统已经更改,因此目前尚不清楚如何附加自定义打字。我应该始终为此创建 NPM 包吗?

提前致谢!

您可以只为您的项目创建本地自定义类型,您可以在其中为 JS 库声明类型。为此,您需要:

  1. 创建目录结构来保存您的类型声明文件,这样您的目录结构看起来类似于:

     .
     ├── custom_typings
     │   └── some-js-lib
     │       └── index.d.ts
     └── tsconfig.json
    
  2. index.d.ts 文件中,为您的 JS 库添加声明:

     declare module 'some-js-lib' {
       export function hello(world: string): void
     }
    
  3. (可选:如果您有 TypeScript >= 4.x,则跳过)compilerOptions 中添加对此类型声明的引用您的 tsconfig.json 部分:

     {
       "compilerOptions": {
         ...
         "typeRoots": ["./node_modules/@types", "./custom_typings"]
       },
       ...
     }
    
  4. 在您的代码中使用声明的模块:

     import { hello } from 'some-js-lib'
    
     hello('world!')