我正在使用动态导入在Typescript中实现工厂模式,以便我可以初始化负载,在运行时初始化(具有必要的组合)所需模块。
我能够像https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html一样动态加载模块
但是它不允许我初始化加载的模块。虽然在开发人员控制台中我可以进行初始化,甚至可以通过初始化模块中组成的子模块和类来无缝地组合它。
苦苦挣扎找到这个解决方案并试了很多东西,但没有解决。在C#中,我们可以使用反射创建它,并创建库和类的实例作为延迟加载而不直接引用它们。
我得到的错误是“//不能使用'new'与表达式类型缺少调用或构造signature.ts(2351)”当我做的时候
let y: Interfaces.IComponent = new comp();
构造它并将其分配给varebale,该对象的接口类型正在实现。
对于组件正在扩展的父类类型也是如此
let x: ComponentImpl = new comp();
请看下面的打字稿代码。
import { Interfaces } from 'shared';
import { ComponentImpl } from 'core';
export default class Factory {
private _loadedModules: Map<string, Interfaces.IComponent> = new Map<string, Interfaces.IComponent>();
private static _instace: Factory;
private constructor() {
}
public static get Instance(): Factory {
return this._instace || (this._instace = new this());
}
public getComponent(component: string): Promise<Interfaces.IComponent> {
return new Promise<Interfaces.IComponent>(async (resolve, reject) => {
let comp = this._loadedModules.get(component);
if (comp !== null) {
comp = await import(`./${component}`);
if (comp) {
// ----------------------------------------------------------------------------
// ** NOTE: On run time I can see the module is loaded corrctly and I can initialze its sub classes in developer console.
// like controller = new comp.controller(); (get console log from constructor)
// controller.sayHello();
// controller.setAPIInstance(new comp.getAPI());
// controller.saveToAPI();
let y: Interfaces.IComponent = new comp(); // Cannot use 'new' with an expression whose type lacks a call or construct signature.ts(2351)
let x: ComponentImpl = new comp(); // Cannot use 'new' with an expression whose type lacks a call or construct signature.ts(2351)
this._loadedModules.set(component, comp);
resolve(comp);
} else {
reject("Unable lo load module");
}
} else {
setTimeout(() => {
resolve(comp);
}, 1);
}
});
}
}
您可以尝试以下适用于我的案例的解决方案:
let x: ComponentImpl = new (comp as typeof ComponentImpl )()
另请参阅TypeScript中的此票证:https://github.com/Microsoft/TypeScript/issues/2081