简体   繁体   中英

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'

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. However because UIObject is an abstract class, this doesn't work as you can't instantiate an abstract class.

What's the best way of doing this?

First, you need to make sure create accepts a class, not an instance.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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