mercredi 3 mars 2021

How to construct TypeScript types for abstract factory pattern

I'm trying to get my head around how I can type the private factories: Record<...>, which will contain key value pairs of a aKey: aFactoryInstance. I've tried Record<string, TemplateFactory>, which has 2 issues; 1. They key is not just any string, but a specific one, and 2. TemplateFactory is the abstract class, and what I have as values are instances of derived classes from that abstract factory one.

I found this SO thread about create a factory class in typescript, which also had my second issue which is the:

Element implicitly has an 'any' type because...

But the comments in there were not applicable here, since they didn't really implement the abstract factory pattern, I got the impression of.

abstract class TemplateFactory {}
class FirstTemplateFactory extends TemplateFactory {}
class SecondTemplateFactory extends TemplateFactory {}

const AvailableTemplate = Object.freeze({
  first: FirstTemplateFactory,
  second: SecondTemplateFactory,
});

class TemplateCreator {
  private factories: Record<string, unknown>; // 👈 How to type this record? It will be an object of: { aKey: aFactoryInstance }

  constructor() {
    this.factories = {};
    Object.keys(AvailableTemplate).forEach((key) => {
      this.factories[key] = new AvailableTemplate[key](); // 👈  "Element implicitly has an 'any' type because expression of type 'string' can't be used to index"
    });
  }
}

Aucun commentaire:

Enregistrer un commentaire