打字稿:使用动态导入的工厂模式不允许构造对象的新实例以进行组成



我正在用动态导入在打字稿中实现工厂模式,以便我可以在运行时初始化负载,初始化(必要组成)。

我能够以https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-44.html

为例,按需动态加载模块

但是,它不允许我初始化加载的模块。尽管在开发人员控制台中我可以进行初始化,甚至可以通过在模块中构成的子模块和类来无缝地组成。

努力寻找该解决方案并尝试了很多事情,但没有解决。在C#中,我们可以使用反射并创建库和类的实例作为懒惰加载而无需直接引用它们。

我遇到的错误是"//无法使用'new'与一个类型缺少呼叫或构造签名的表达式。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

最新更新