77

根据这篇文章,typescript 2.0 的打字系统已经改变,所以现在还不清楚如何附加自定义打字。我应该总是为此创建 NPM 包吗?

先感谢您!

4

1 回答 1

141

您可以仅为您的项目创建本地自定义类型,您可以在其中声明 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!')
    
于 2017-01-17T21:19:53.123 回答