Monday, 22 October 2018

Cast typename to type in typescript

I want to cast a string with a typename to a type without an explicit mapping (I need the type for an angular component factory).

With a mapping this is pretty straightforward:

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

The problem is that I have many components that need to be mapped manually and it would be nice if I were able to omit the map.

Solutions I found, that are sadly not possible due to minification:

  • using eval() (also this would be really dirty and unsafe)

  • using window['Type1']

The rest of the solutions I found were mostly dead threads or provided the mapping as the best possibility. Do you have any Ideas how to solve this? Is this even possible?



from Cast typename to type in typescript

No comments:

Post a Comment