I'm looking to dynamically instantiate components in my code, but I seem to be struggling with the implementation. Do I need to use "cast" as I understand it or is there a more elegant solution?
abstract class Component{
abstract mount(): void;
}
class ComponentA extends Component{
mount(){}
send(){}
}
class ComponentB extends Component{
mount(){}
}
type Components = {
componentA: ComponentA,
componentB: ComponentB
}
const componentsName = [ComponentA, ComponentB];
const instances = {} as Components;
for(const component of componentsName){
instances[component.name] = new component(); //how to cast?
//Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Components'.
//No index signature with a parameter of type 'string' was found on type 'Components'.(7053)
}
function getComponent <T extends keyof Components>(componentName: T): Components[T] {
return instances[componentName];
}
//test 1
const componentA = instances.componentA
const componentB = instances.componentB
//test 2
const componentA2 = getComponent("componentA").send //mount | send
const componentB2 = getComponent("componentB").mount //only mount