简体   繁体   English

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

[英]How to add custom “typings” in typescript 2.0 / 3.0

According to this article typings system for typescript 2.0 has changed and so it is not clear how to attach custom typings now.根据这篇文章,typescript 2.0 的打字系统已经改变,所以现在不清楚如何附加自定义打字。 Should I always create NPM package for that?我应该总是为此创建 NPM 包吗?

Thank you in advance!提前谢谢你!

You can create local custom typings just for your project, where you can declare types for JS libraries.您可以仅为您的项目创建本地自定义类型,您可以在其中声明 JS 库的类型。 For that, you need to:为此,您需要:

  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.ts file, add a declaration for your JS library:index.d.ts文件中,为您的 JS 库添加一个声明:

     declare module 'some-js-lib' { export function hello(world: string): void }
  3. (Optional: skip if you have TypeScript >= 4.x) Add a reference to this type declaration in the compilerOptions section of your tsconfig.json : (可选:如果您有 TypeScript >= 4.x,请跳过)tsconfig.jsoncompilerOptions部分中添加对此类型声明的引用:

     { "compilerOptions": { ... "typeRoots": ["./node_modules/@types", "./custom_typings"] }, ... }
  4. Use the declared module in your code:在代码中使用声明的模块:

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

Assuming you have your external js package installed under node_modules, I think there are two options: 假设您在node_modules下安装了外部js包,我认为有两种选择:

  • provide a typescript declaration file in the package , and add a reference to it: 在包中提供一个打字稿声明文件 ,并添加对它的引用:

     // node_modules/secret-package/index.d.ts export interface SecretInterface { // ¯\\_(ツ)_/¯ } 

    And reference the typings file in the package.json: 并引用package.json中的typings文件:

     // node_modules/secret-package/package.json { ..., "typings": "./index.d.ts", ..., } 
  • augment the module in a declaration file of your project 在项目的声明文件中扩充模块

     // index.d.ts declare module 'secret-package' { interface SecretInterface { // ¯\\_(ツ)_/¯ } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM