简体   繁体   中英

Include custom Typings in index.d.ts npm module

I am currently writing a plugin for mongoose . Now as I am using TypeScript I have the following situation. 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

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

will extend the existing interface via Declaration Merging

I include the typeRoot in my tsconfig

tsconfig.json

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

When building my npm module I use the --declare flag to export types as well. 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.

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?

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

Instead of writing a .d.ts file just switch to a regular .ts file. So in my case

src/types/mongoose.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

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.

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.

You can also do like this in one of your main root file-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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