1

我正在使用动态导入在 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);
                }

            });
        }
    }
4

1 回答 1

0

您可以尝试以下适用于我的解决方案:

let x: ComponentImpl =  new (comp as typeof ComponentImpl )()

另请参阅 TypeScript 的这张票:https ://github.com/Microsoft/TypeScript/issues/2081

于 2019-03-14T07:05:33.197 回答