typescript 如何在打字稿 2.0 / 3.0 中添加自定义“打字”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38971984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:17:13  来源:igfitidea点击:

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

typescripttypescript2.0

提问by Lu4

According to thisarticle typings system for typescript 2.0 has changed and so it is not clear how to attach custom typings now. Should I always create NPM package for that?

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

Thank you in advance!

先感谢您!

回答by MisterMetaphor

You can create local custom typings just for your project, where you can declare types for JS libraries. For that, you need to:

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

  1. Create directory structure to keep your type declaration files so that your directory structure looks similar to this:

    .
    ├── custom_typings
    │?? └── some-js-lib
    │??     └── index.d.ts
    └── tsconfig.json
    
  2. In the index.d.tsfile, add a declaration for your JS library:

    declare module 'some-js-lib' {
      export function hello(world: string): void
    }
    
  3. Add a reference to this type declaration in the compilerOptionssection of your tsconfig.json:

    {
      "compilerOptions": {
        ...
        "typeRoots": ["./node_modules/@types", "./custom_typings"]
      },
      ...
    }
    
  4. Use the declared module in your code:

    import { hello } from 'some-js-lib'
    
    hello('world!')
    
  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您的部分中添加对此类型声明的引用tsconfig.json

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

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