Reputation: 923
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
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