Andrew Carreiro
Andrew Carreiro

Reputation: 1567

Abstract class A cannot instantiate new instances of abstract class B

I'd like to set up a structure where I can create new classes that extend from ClassReturner and TheClass in the code below, but I'm getting an error.

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;
    }

}

Why is this not allowed? Shouldn't the fact that TClass extends TheClass confirm that it has a constructor?

Upvotes: 1

Views: 301

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164129

No, returningClass: TClass is an instance of a class that extends TheClass.
To have the ctor you need: { new (name: string): TheClass }.

So this should work for you:

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

Upvotes: 2

Related Questions