4

I am trying to create an instance of a class, but the compile-time error is saying:

Cannot create an instance of the abstract class 'QueueProcess'.

However, I am not creating an instance of it, I am creating an an instance of a class that extends QueueProcess. So, why am I getting this error?

export class Queue<T extends QueueProcess> {

    private _queue: T[] = []

    private async runFirstProcess() {
      let process = new this._queue[0]
    }

}

export abstract class QueueProcess {

}

The code once compiled works fine, it is just throwing that compile-time error.

4
  • isn't new T of type QueueProcess, not the derived type? Commented Oct 16, 2017 at 21:00
  • I'm not sure what you mean... Commented Oct 16, 2017 at 21:03
  • Shouldn't it be,at least, export class Queue extends QueueProcess implements T. It seems really weird while you are using that "arrows" around extends Commented Oct 16, 2017 at 21:12
  • because Queue doesn't extend QueueProcess, it holds an array of QueueProcess's Commented Oct 16, 2017 at 21:13

3 Answers 3

5

So, first of all, the line T extends QueueProcess means that T is an instance of QueueProcess, which won't be newable. To access the constructor type, you need T extends typeof QueueProcess.

But that won't work anyway, since QueueProcess itself extends QueueProcess, and since it's abstract, typescript will complain about that. So instead, make T extend a newable function that returns a QueueProcess, eg:

export class Queue<T extends new () => QueueProcess> {

    private _queue: T[] = []

    private async runFirstProcess() {
        let process = new this._queue[0]()
    }

}

export abstract class QueueProcess {

}
Sign up to request clarification or add additional context in comments.

2 Comments

Okay, that makes sense. I didn't know that you could do <T extends new() => xxx>
new () => SomeType is a shorthand syntax for an interface with construct signature, also called "newable type": {new(): SomeType}
0

You can use the Constructor helper from type-fest:

export class Queue<T extends Constructor<QueueProcess>> {

    private _queue: T[] = []

    private async runFirstProcess() {
        let process = new this._queue[0]()
    }

}

export abstract class QueueProcess {

}

Comments

-1

I rewrote your code a bit to satisfy the code analyzer. It's placed here. However, your code has issue with new this._queue[0]. Also, extension of class that is placed after current is a bad idea.

Result code is

export abstract class QueueProcess {

}

export class Queue<T> extends QueueProcess {

    private _queue: T[] = []

    private async runFirstProcess() {
      let process = new this._queue[0]
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.