How to use a type from an optional dependency in a

2019-08-10 03:30发布

问题:

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.