简体   繁体   English

在 index.d.ts npm 模块中包含自定义类型

[英]Include custom Typings in index.d.ts npm module

I am currently writing a plugin for mongoose .我目前正在为mongoose写一个插件。 Now as I am using TypeScript I have the following situation.现在,当我使用 TypeScript 时,我遇到了以下情况。 I have to extend the existing Interface.我必须扩展现有的界面。 This is no problem.这没问题。 For the sake of completeness I'll write it down nontheless尽管如此,为了完整起见,我还是会把它写下来

src/typings/mongoose.d.ts src/打字/mongoose.d.ts

declare module 'mongoose' {
  export interface SomeExistingMongooseInterface {
    MyNewOption?: FancyOptionInterface
  }
}

will extend the existing interface via Declaration Merging将通过声明合并扩展现有接口

I include the typeRoot in my tsconfig我在我的 tsconfig 中包含了 typeRoot

tsconfig.json tsconfig.json

"compilerOptions" : {
  ...
  "typeRoots": {
    "src/types",
    "node_modules/@types"
  }
}

When building my npm module I use the --declare flag to export types as well.在构建我的 npm 模块时,我也使用 --declare 标志来导出类型。 Now the problem is, that the custom typings are nowhere to be found.现在的问题是,找不到自定义类型。 Of course I could add the contents of it manually to my.当然我可以手动将它的内容添加到我的。 /dist/index.d.ts which would work but this is not a really an option since it cannot be automated and would leave a lot of room for errors. /dist/index.d.ts可以工作,但这不是一个真正的选择,因为它不能自动化并且会留下很多错误空间。

Is there any best practice to do this in a way that it works with the typescript compiler or at least an npm module that can take care of this?是否有任何最佳实践以与 typescript 编译器或至少 npm 模块一起使用的方式来执行此操作?

OK.好的。 I finally got it to work.我终于让它工作了。 Here's what I did to implement这是我为实现所做的

Custom Typings for third party npm module in your npm module npm 模块中第三方 npm 模块的自定义类型

Instead of writing a .d.ts file just switch to a regular .ts file.无需编写 .d.ts 文件,只需切换到常规 .ts 文件即可。 So in my case所以就我而言

src/types/mongoose.ts源代码/类型/猫鼬.ts

declare module 'mongoose' {
  export interface SomeExistingMongooseInterface {
    MyNewOption?: FancyOptionInterface
  }
}

The second step is to import this file in your application.第二步是在您的应用程序中导入此文件。 I just found it convenient to add it in the root file so我只是发现将它添加到根文件中很方便

src/index.ts源代码/索引.ts

import "./types/mongoose"

And that is already it.这已经是了。 Nothing more to do.没什么可做的。 When building the application the typescript compiler will now generade a mongoose.d.ts file in the dist/src/types folder that will be published afterwards.当构建应用程序的打字稿编译器现在将在dist / src目录/类型generade一个mongoose.d.ts文件夹,将在之后公布。

Everything will work fine and if you choose to publish this to npm your users will also benefit from having the third party interface beeing extended.一切正常,如果您选择将其发布到 npm,您的用户也将受益于第三方界面的扩展。

You can also do like this in one of your main root file-您也可以在主根文件之一中执行此操作-

/// <reference path="./path/to/your/src/typings/mongoose.d.ts" />

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

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