在typecript中输入的类型名称

And*_*ned 5 typescript angular

我想将一个带有typename的字符串转换为没有显式映射的类型(我需要一个角度组件工厂的类型).

通过映射,这非常简单:

public readonly typeMap: Map<string, Type<{}>> = new Map<string, Type<{}>>([
  ['Type1', Type1],
  ['Type2', Type2]
]);
Run Code Online (Sandbox Code Playgroud)

问题是我有许多需要手动映射的组件,如果我能省略映射就会很好.

我发现的解决方案,由于缩小而遗憾地是不可能的:

  • 使用eval()(这也会非常脏和不安全)

  • 使用窗口['Type1']

我找到的其余解决方案大部分是死线程或提供映射作为最佳可能性.你有什么想法如何解决这个问题?这甚至可能吗?

And*_*ned 1

因此,在 @Julian 的帮助下,我自己想出了一个很好的解决方案:我用一个类装饰器替换了映射,该类装饰器给出了类型字符串,并注释了我想要用它生成的每个类型。然后,在装饰器实现中,我将类型添加到地图中,现在是动态填充的。

该解决方案不会手动映射每个组件,但我认为它比我以前的解决方案要好得多,因为映射现在与组件位于同一位置,并且不容易被忘记。

// Empty mapping, filled at runtime
export const typeMap: Map<string, Type<{}>> = new Map<string, Type<{}>>();

// Classes that can be generated
@Type('Type1')
export class Type1 {}

@Type('Type2')
export class Type2 {}

// Decorator
export function Type(componentType: string) {
  return (target) => { typeMap.set(componentType, <Type<{}>>target); };
}
Run Code Online (Sandbox Code Playgroud)