简体   繁体   English

打字稿中抽象类的依赖注入

[英]Dependency injection of abstract class in typescript

I am new to typescript and I'm trying to use dependency injection to create UI Objects that extend a base abstract UIObject class, but I'm hitting the error 'Cannot create an instance of an abstract class' 我是TypeScript的新手,正在尝试使用依赖项注入来创建扩展基本抽象UIObject类的UI对象,但遇到错误“无法创建抽象类的实例”

Here is a simplified example: 这是一个简化的示例:

abstract class UIObject {
// Some methods
}

class Cursor extends UIObject {
// Some other methods
}

function create (UIObjectClass: typeof UIObject){
  return new UIObjectClass()
}

What I want is for the create function to be able to take any class that extends UIObject as a parameter, and create an instance of that class. 我想要的是create函数能够将扩展UIObject的任何类作为参数,并创建该类的实例。 However because UIObject is an abstract class, this doesn't work as you can't instantiate an abstract class. 但是,由于UIObject是抽象类,因此无法工作,因为您无法实例化抽象类。

What's the best way of doing this? 最好的方法是什么?

First, you need to make sure create accepts a class, not an instance. 首先,您需要确保create接受一个类,而不是一个实例。

interface Constructable {
  new (...args: any[]): any;
}

function create<T extends Constructable>(UIObjectClass: T): InstanceType<T> {
  return new UIObjectClass();
}

This will make TypeScript accept only concrete classes. 这将使TypeScript仅接受具体的类。

create(UIObject);     // Error! Can't use an abstract class here.
create(Cursor);       // OK
create(new Cursor()); // Error! We should be passing a class, not an instance.

I haven't found a way to ensure the argument — UIObjectClass — inherits from UIObject though. 我还没有找到一种方法来确保自变量UIObjectClass继承自UIObject

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM