Takeshi Tokugawa YD
Takeshi Tokugawa YD

Reputation: 923

How to annotate "typeof" inheritor of certain class (not it's instance) in TypeScript?

Assume that

abstract class Controller {}

class ProductController extends Controller {}
class CommentController extends Controller {}

Currently the type annotation of parameter of testFunction means "class Controller itself, not it's instance":

function testFunction(ControllerClass: typeof Controller): void {
   const instance: Controller = new ControllerClass();
}

The function is invalid, because we can not create the instances of abstract class.

Now how to specify "type of any inheritor of Controller"? I don't mean the instances, I mean the classes like ProductController or CommentController.

function testFunction(SpecificControllerClass: typeof /*???*/): void {
   const controllerInstance: /*???*/ = new SpecificControllerClass();
}

I don't know how generics could be used in this case.

Upvotes: 0

Views: 77

Answers (1)

Wang Weixuan
Wang Weixuan

Reputation: 351

Think of the parameter as a constructor instead of a class:

function testFunction(ControllerClass: new () => Controller): void {
  const instance: Controller = new ControllerClass();
}
testFunction(Controller) // Error: Cannot assign an abstract constructor type to a non-abstract constructor type.

testFunction(ProductController) // Passes

Upvotes: 2

Related Questions