【问题标题】:Dependency injection of abstract class in typescript打字稿中抽象类的依赖注入
【发布时间】:2019-05-10 13:20:29
【问题描述】:

我是 typescript 的新手,我正在尝试使用依赖注入来创建扩展基本抽象 UIObject 类的 UI 对象,但我遇到了错误“无法创建抽象类的实例”

这是一个简化的例子:

abstract class UIObject {
// Some methods
}

class Cursor extends UIObject {
// Some other methods
}

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

我想要的是 create 函数能够将任何扩展 UIObject 的类作为参数,并创建该类的实例。但是因为 UIObject 是一个抽象类,所以这不起作用,因为你不能实例化一个抽象类。

最好的方法是什么?

【问题讨论】:

    标签: typescript dependencies abstract code-injection


    【解决方案1】:

    首先,您需要确保create 接受一个类,而不是一个实例。

    interface Constructable {
      new (...args: any[]): any;
    }
    
    function create<T extends Constructable>(UIObjectClass: T): InstanceType<T> {
      return new UIObjectClass();
    }
    

    这将使 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.
    

    我还没有找到一种方法来确保参数 — UIObjectClass — 继承自 UIObject

    【讨论】:

    猜你喜欢
    • 2017-01-06
    • 2021-09-01
    • 1970-01-01
    • 2016-10-26
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    相关资源
    最近更新 更多