Search code examples
typescript

Can TypeScript retrieve the type of an imported module by its path?


I'm trying to write a wrapper around jest.isolateModules called test.isolated(). The function takes in an array of strings representing the modules the test would like imported, followed by the usual arguments (name, fn, timeout), then injects an object with each of the imported modules by name as the first parameter of fn.

The body of test.isolated is easy enough to write using proxies. I want to know how to strongly type the first argument.

Somehow VS Code's TypeScript engine can determine the type of an imported module's exports. Is it possible to infer that type (the return type of require()) based off the path to the module?

My first attempt was:

type ModuleType<M extends string> = 
  ((m: M) => ReturnType<NodeRequire>) extends ((m: M) => infer U) ? U : never;

type T = ModuleType<'fs'>;

Oddly enough, T is typeof Electron no matter what I put in for M. It looks like ReturnType<NodeRequire> is typeof Electron itself in my project.

Second attempt:

type ModuleType<M extends string> = 
  ((m: M) => NodeRequire['main']['exports']) extends ((m: M) => infer U) ? U : never;

type T = ModuleType<'fs'>; // => any

Ideas? Or is this simply not possible?

Edit: I've discovered that the return type of require() is always any. Only the import syntax infers a type.


Solution

  • Seems to be a frequent feature request which is impossible right now (and I'd like it too). E.g.