Imagine you have a structure of TypeScript code and assets stored at a specific URL, like between a CDN and a debug location. You want to import the main module and ensure the rest of the structure is imported correctly only when needed, without repeating the loading path multiple times.
In vanilla JavaScript, you might achieve this with code similar to:
export class MyModule {
private dependentModulePromise;
constructor(rootpath) {
this.dependentModulePromise = import(rootpath + '/dependentModule');
}
}
However, in TypeScript, you'd aim for maximum type safety. Using a type assertion is necessary for the dynamic string import, but how can you inform TypeScript about the type being loaded without conflicts or synchronously bundling the module with tools like Webpack?
An attempt was made with the following approach:
import * as DependentModule from '/dependentModule';
export class MyModule {
private dependentModulePromise: Promise<DependentModule>;
constructor(rootpath) {
this.dependentModulePromise = import(rootpath + '/dependentModule') as Promise<DependentModule>;
}
}
Unfortunately, an error occurs stating that the namespace DependentModule
cannot be used as a type.