I'm currently working on creating a function, test.isolated()
, which wraps around jest.isolateModules
. This function takes an array of strings representing the modules to be imported, along with the usual arguments (name
, fn
, timeout
), and then injects an object containing each imported module by name as the first parameter of fn
.
The implementation of test.isolated()
using proxies is straightforward. However, I am trying to figure out how to strongly type the first argument.
I have noticed that VS Code's TypeScript engine can determine the type of exports from an imported module. Is it feasible to infer this type (the return type of require()
) based on the module path?
In my initial attempt:
type ModuleType<M extends string> =
((m: M) => ReturnType<NodeRequire>) extends ((m: M) => infer U) ? U : never;
type T = ModuleType<'fs'>;
Interestingly, regardless of what value I provide for M
, T
always resolves to typeof Electron
. It seems like in my project, ReturnType<NodeRequire>
itself is typeof Electron
.
In my second attempt:
type ModuleType<M extends string> =
((m: M) => NodeRequire['main']['exports']) extends ((m: M) => infer U) ? U : never;
type T = ModuleType<'fs'>; // => any
Any thoughts or suggestions? Or is this type inference task impossible?
Edit:
Upon further investigation, I have found that the return type of require()
is always any
. Only the import
syntax can infer a type.