首页 > 解决方案 > 打字稿中具有工厂设计的通用类

问题描述

我可以知道为什么下面的代码行不起作用,它输出

类型“instanceA”不可分配给类型“T”。“instanceA”可分配给“T”类型的约束,但“T”可以用约束“A”的不同子类型来实例化。

interface A {}

class instanceA implements A {}

type instanceComponent = (typeof instanceA);

class factory<T extends A = A> {
    private _methods : instanceComponent[] = [instanceA];
    private _components: {[key:string] : T } = {};
    constructor() 
    {
    }
    createInstance(name: string ) : T
    {
        if(typeof this._components[name] != "undefined")
        {
           return new this._methods[0](); //error warning in this line
        }
        throw new Error(`Instance [${name}] not supported.`);
    }
}

标签: typescriptgenericsfactory-pattern

解决方案


是的,所以解决方案是

interface A { code :string }

interface B extends A {}

class instanceA implements A {
    static NAME : string = "A";
    code = instanceA.NAME;
}
class instanceB implements B {
    static NAME : string = "B";
    code = instanceB.NAME;
}
type instanceComponent = (typeof instanceA)|(typeof instanceB);

class factory<T extends A> {
    private _methods : (instanceComponent)[] = [instanceA, instanceB];
    private _components: {[key:string] : T } = {};
    constructor() 
    {
    }
    createInstance(name: string ) : T
    {
        if(typeof this._components[name] == undefined)
        {
            const obj  = this._methods.find(e => e.NAME === name);
            if(obj != undefined)
            {
                const s = new obj();
                this._components[s.code] = s as T;
            }
            throw new Error("errr");
        }
        return this._components[name];
    }
}

推荐阅读