I'm trying to instantiate an abstract class, searching around suggests this isn't possible without a bunch of odd hoops but I can't find a way to make it work for my situation
What I'm trying to do is create a generic abstract factory that has a non-abstract function which generates a new instance of the generic type
abstract class GenericItemFactory<T> {
create(attribute: any): T {
return new T(attribute);
}
}
This seems impossible in TypeScript from my searching, please correct me if I'm wrong
Since this isn't possible, and since I have 6 (and growing) instances of the GenericItemFactory, I end up needing to write exactly identical functions for create
. Writing the exact same code 6 times screams at me the need for abstraction but I can't figure out how to do it.
I saw a few tricks of passing in the type and being able to create a generic instance but couldn't figure out how to adapt to my use
These as a suite of Factors that expose a create
method, and are exported in an object like
class ItemA extends Item {
attribute: any;
}
class ItemAFactory extends GenericItemFactory {
create(attribute: any): ItemA {
return new ItemA(attribute);
}
}
... repeated for each Item Type! and then exported as
const items: { [itemKey: string]: GenericItemFactory } = {
itemA: new ItemAFactory(),
itemB: new ItemBFactory(),
itemC: new ItemCFactory(),
...
}
How can I instantiate that generic type like I'm trying, or otherwise restructure my factor to be able to accomplish? Thanks!