2017-03-29 139 views
1

我正在写一个类型工厂吐出不同类型的基础上,将字符串标识符与一般的回报类的引用,例如:如何打字稿

export class InputComponent<T> { 
    constructor(public value: T) { 
    } 
} 

export const getComponentClass = (identifier: string) => { 
    switch (identifier) { 
     case 'textarea': 
      return Textarea; 
     case 'input:number': 
      // here to return InputComponent<number> 
     case 'input:binary': 
      return Radio; 
     case 'input:string': 
     default: 
      // here I want to return something like InputComponent<string> 
    } 
} 

然后,我将使用它像(很简单例子来说明我怎么想的事情发生,在我们使用ComponentFactoryResolver创建动态组件)

const classdef = getComponentClass('input:text'); 
const input = new classdef('hello, world'); 

有没有办法真正做到了真正的项目?或者我必须采用子类方法为每种类型指定一个类?

谢谢。

回答

0

为什么即使有getComponentClass函数也可以用适当的类型创建一个新的类实例。

const input = new InputComponent<string>("hello world"); 
+0

在我的应用程序中,表def来自后端并在应用程序之间共享,所以我需要一些东西来确定类的类型。另外我在运行时使用ComponentFactoryResolver创建动态组件 – hjbolide

+0

编辑原始问题以清楚说明:D – hjbolide