Currently, I'm in the process of refactoring some code and had a question regarding the possibility of declaring and initializing a dictionary that contains factory functions, with each function being associated with an enumerator key. This setup would allow for easy lookup and invocation of the factory functions. Alternatively, I am open to suggestions if there is a more elegant solution that I might be overlooking. I came across this helpful answer which guided me on how to declare and initialize a typed dictionary, but I have concerns about whether I've correctly defined the signature so that the key is a number and the value is a function. To illustrate my query, I have simplified the code into a generic example - though it may seem contrived, it serves its purpose effectively.
// Various types are enumerated as I have multiple type lists that I want to implement as arrays of enumerators
enum ElementType {
TypeA,
TypeB,
TypeC
}
// Here, I aim to define a dictionary where the keys are numbers and the values are functions
var ElementFactory: { [elementType: number]: () => {}; };
// Subsequently, I specify these factory functions to create new objects
ElementFactory[ElementType.TypeA] = () => new ElementOfTypeA();
ElementFactory[ElementType.TypeB] = () => new ElementOfTypeB();
ElementFactory[ElementType.TypeC] = () => new ElementOfTypeC();
// Finally, I desire to call these functions to obtain instances of declared objects as shown in the code block above
var a = ElementFactory[ElementType.TypeA]();
var b = ElementFactory[ElementType.TypeB]();
var c = ElementFactory[ElementType.TypeC]();