One of my challenges is to create a versatile factory method using typescript.
The main objective is to initialize a class based on its name using generics, instead of employing if/else or switch statements.
I am aiming for similar functionality as this example:
document.createElement("p");
createElement<K extends keyof HTMLElementTagNameMap>(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K];
interface HTMLElementTagNameMap {
"a": HTMLAnchorElement;
"abbr": HTMLElement;
"address": HTMLElement;
"applet": HTMLAppletElement;
...
}
I encountered an obstacle when attempting to instantiate a class type:
class A {
constructor(private name:string,private id:number){
}
}
class B extends A{
}
class C extends A{
}
interface stringToClassMap{
'A':A;
'B':B;
'C':C;
}
// Should return a new instance every time
const obj: stringToClassMap = {A:new A('x',123),B:new B('x',123),C:new C('x',123)}
function creator<K extends keyof stringToClassMap>(key:K): A{
return new obj[key]();
}
Thank you!