How to use a type from an optional dependency in a declaration file?

你说的曾经没有我的故事 提交于 2019-12-24 17:27:44

问题


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.

来源:https://stackoverflow.com/questions/52795354/how-to-use-a-type-from-an-optional-dependency-in-a-declaration-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!