4

I have a JS library that does something like so:

let OptionalLib;
function foo() {
  OptionalLib = require('optionallib');
  // Do stuff...
  return (something from optional lib);
}

then I add typings in a .d.ts file:

declare module 'mylib' {
  import { Bar } from 'optionallib';
  export function foo(): Bar;
}

the problem with this is that if the optional library is not installed, TS will complain about not being able to import it, even though it's optional. I tried doing this in order to have the typings for the library when it's not installed:

declare module 'optionallib' {
  interface Bar {}
}

but the problem with this is that it seems to replace the actual module completely when it is installed (no declaration merging?), so if it exported Baz, it won't be found.

So how should I handle this problem? I am aware that I can split the part relying on this optional library to another library, but I feel it would be more convenient to leave it in since its so small.

comp
  • 106
  • 1
  • 4
  • Have you resolved this issue? I am currently wondering about this same problem – Alexander Dec 13 '18 at 17:31
  • I have not, I have just typed it as `any` for now. – comp Dec 14 '18 at 22:24
  • I cant believe this does not exist. Seriously. – Kevin Upton Aug 13 '20 at 04:10
  • Does this answer your question? [How do I handle optional peer dependencies when publishing a TypeScript package?](https://stackoverflow.com/questions/54392809/how-do-i-handle-optional-peer-dependencies-when-publishing-a-typescript-package) – Coderer Nov 24 '21 at 09:49
  • I'm not working on this problem anymore, but creating an interface that fits both seems like a good idea. – comp Apr 02 '22 at 23:55

0 Answers0