1

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!

Joshua Ohana
  • 5,613
  • 12
  • 56
  • 112
  • It seems you're mixing up types and values. How do you expect `ItemFactory` to know what class to call to create a new instance? – Etheryte Aug 09 '22 at 18:36
  • You need to pass a class constructor into `GenericItemFactory`, as shown [here](https://tsplay.dev/mLqKVW). See the answers to the linked question for more information. – jcalz Aug 09 '22 at 18:49
  • 1
    I tried out the answers from the solution on [the TS Playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBAxsD2AnAPAFQHxQLxQN4CgoioA7CAdygAoBDYYRASwCMBXYCALihpJAEpuqANz4AvvhrMAzgxpxYAGxrTpUAOIQyTGAEkOAWwBi8hIhB5CUWXUYxYiCHQhp0tekzYduvEABpYM244JFdBKFRLYmJHYFZEElIKQKR3BhZ2CH4eNRErCQkYZVUofQgDAEEo4hh4EllEVhDENM9Mzl9sgmjo4AALRmkAOjp0r2gcUbaOUWiJaKmM7x4+UUK62ShGQwqTZoscTW07MuNTJBAhmEdnKgAiKbuA04r+YSA) with a minor change (made `create` static and moved the generic to that function), and it seems to work pretty slick. – Heretic Monkey Aug 09 '22 at 18:57

0 Answers0