假设
abstract class Controller {}
class ProductController extends Controller {}
class CommentController extends Controller {}
当前CCD_ 1的参数类型注释表示";类控制器本身,而不是它的实例":
function testFunction(ControllerClass: typeof Controller): void {
const instance: Controller = new ControllerClass();
}
函数无效,因为我们无法创建抽象类的实例。
现在如何指定";Controller
的任何继承人的类型";?我指的不是实例,而是像ProductController
或CommentController
这样的类。
function testFunction(SpecificControllerClass: typeof /*???*/): void {
const controllerInstance: /*???*/ = new SpecificControllerClass();
}
我不知道在这种情况下如何使用泛型。
将参数视为构造函数,而不是类:
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