简体   繁体   English

从类型名称创建打字稿类型

[英]Create typescript type from type name

I'm trying to create format feature in angular where the format name is passed to a format child component. 我正在尝试以角度创建格式功能,其中将格式名称传递给格式子组件。 This format component is created via 该格式组件是通过以下方式创建的

let componentFactory = componentFactoryResolver.resolveComponentFactory(typeOfFormatComponent);

So, to make it configurable I need to pass the typeOfFormatComponent as a string - say - 'AddressFormatComponent'. 因此,要使其可配置,我需要将typeOfFormatComponent作为字符串传递-例如-'AddressFormatComponent'。

How do I turn the string 'AddressFormatComponent' into the type AddressFormatComponent for the resolveComponentFactory call? 如何将字符串“ AddressFormatComponent”转换为resolveComponentFactory调用的AddressFormatComponent类型?

You can declare an interface for all FormatComponents: 您可以为所有FormatComponents声明一个接口:

interface FormatComponents {
    AddressFormatComponent: FormatComponent;
    ...
}
resolveComponentFactory(component: keyof FormatComponents) {
    let formatComponent = FormatComponents[component]; // This will work and be typed correctly.
}

This allows you to have compile time checking of types by enforcing that the stings match. 这样可以通过强制匹配字符串来进行类型的编译时检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM