Issue
TypeScript's import()
expression allows to lazily load code at runtime. I can, for instance, call await import('@my-app/a/b')
and receive an object that has exactly the members exported from the referenced source module.
This is type-safe; the TypeScript compiler knows at design time what members will be available on the returned object based on the path.
Is there any way to wrap this import()
expression and still get back the strongly-typed object?
A use case would be so I can perform some standard operations on the returned object before it is handed back to the calling code.
For example:
Using the bare lazy-loaded module:
const module = await import('@my-app/a/b');
module.doSomething();
Using the lazy-loaded module only after standard operations have been done:
const module = await loadAndProcessModule('@my-app/a/b');
module.doSomething();
The question is how to implement, or at least declare, loadAndProcessModule
without breaking type-safety.
Solution
I think in order to do this, you would need to be able to express typeof import("module-specifier")
as a generic. e.g. your loadAndProcessModule
function signature would need to look something like this:
function loadAndProcessModule<T extends string>(moduleSpecifier: T): typeof import(T) {
// ...
}
Unfortunately, this is not possible in Typescript today - see this question and this open feature request.
Answered By - Andrew Stegmaier
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.