抽象类A无法实例化抽象类B的新实例

时间:2016-05-15 17:29:59

标签: typescript

我想建立一个结构,我可以在下面的代码中创建从ClassReturner和TheClass扩展的新类,但是我收到了错误。

abstract class ClassReturner <TClass extends TheClass> {
    private returningClass : TClass;

    constructor ( r : TClass ){
        this.returningClass = r;
    }

    public getAnotherClass (){
        //ERROR BELOW: Cannot use 'new' with an expression whose type lacks a call or construct signature.
        return new this.returningClass("John Doe");

    }
}

abstract class TheClass {
    private whoiam: string;

    constructor ( w : string ){
        this.whoiam = w;
    }

}

为什么不允许这样做? TClass扩展TheClass的事实不应该确认它有构造函数吗?

1 个答案:

答案 0 :(得分:2)

不,returningClass: TClass是扩展TheClass的类的实例 要拥有你需要的人:{ new (name: string): TheClass }

所以这对你有用:

abstract class TheClass {
    private whoiam: string;

    constructor(w: string) {
        this.whoiam = w;
    }
}

interface TheClassConstructor<T extends TheClass> {
    new(name: string): T;
}

abstract class ClassReturner<TClass extends TheClass> {
    private returningClass: TheClassConstructor<TClass>;

    constructor(r: TheClassConstructor<TClass>) {
        this.returningClass = r;
    }

    public getAnotherClass() {
        return new this.returningClass("John Doe");
    }
}

Code in playground