如何添加自定义" typings"在typescript 2.0中

时间:2016-08-16 10:03:31

标签: typescript typescript2.0

根据this文章类型,打字稿2.0的系统已经改变,因此现在不清楚如何附加自定义类型。我应该总是为此创建NPM包吗?

提前谢谢!

2 个答案:

答案 0 :(得分:56)

您可以为项目创建本地自定义类型,您可以在其中声明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. compilerOptions的{​​{1}}部分添加对此类型声明的引用:

    tsconfig.json
  4. 在代码中使用声明的模块:

    {
      "compilerOptions": {
        ...
        "typeRoots": ["node_modules/@types", "custom_typings"]
      },
      ...
    }
    

答案 1 :(得分:1)

假设您在node_modules下安装了外部js包,我认为有两种选择:

  • 在包中提供打字稿声明文件,并添加对它的引用:

    .

    并参考package.json中的typings文件:

    // node_modules/secret-package/index.d.ts
    export interface SecretInterface {
      // ¯\_(ツ)_/¯
    }
    
  • 在项目的声明文件中扩充模块

    // node_modules/secret-package/package.json
    {
       ..., 
       "typings": "./index.d.ts",
       ...,
    }