在Angular中,我得到一个String并想将其转换为Type / Component。例如,我得到“ ListComponent”并想将ListComponent添加到应用程序中。 我不想将它们映射到Map或其他内容中。是否可以从字符串中获取类型?
stringComponent = "ListComponent";
typeComponent = *transform "ListComponent" to ListComponent;
method(typeComponent);
答案 0 :(得分:0)
也许像这样:
class ListComponent {
foo = 'bar'
}
class LolComponent {}
const componentsMap = {
ListComponent,
LolComponent
}
type ComponentName = keyof typeof componentsMap;
function convertStringToComponent<Name extends ComponentName>(name: Name): (typeof componentsMap)[Name] {
return componentsMap[name];
}
const CompByName = convertStringToComponent('ListComponent');
const instance = new CompByName();
instance.foo; // ok!