实例化接口类型的变量

时间:2018-10-09 21:56:52

标签: typescript

我想在Typescript中动态实例化一个类

这是一个代码示例

interface IHtmlField {
  name: string
}

class TextInput implements IHtmlField {
  public name: string
}

class FileInput implements IHtmlField {
  public name: string
}

const fields: {[type: string]: IHtmlField} = {
  text: TextInput,
  file: FileInput
}

const type = 'text' // dynamic variable
const fieldCls = fields[type]
new fieldCls()

我遇到此错误
Cannot use 'new' with an expression whose type lacks a call or construct signature.

这是因为我要实例化的变量的类型为IHtmlField

是否有解决方法或更好的方法?

2 个答案:

答案 0 :(得分:2)

fields的属性类型不应是IHtmlField实例,而应是构造IHtmlField子类的构造函数:

const fields: {[type: string]: {new(): IHtmlField}} = {
  text: TextInput,
  file: FileInput
}

答案 1 :(得分:0)

看起来像这样工作:

interface IHtmlField {
    name: string
}

class TextInput implements IHtmlField {
    public name: string
}

class FileInput implements IHtmlField {
    public name: string
}

const fields: { [type: string]: IHtmlField } = {
    text: new TextInput(),
    file: new FileInput()
}

const type = 'text' // dynamic variable
const fieldCls = fields[type]

console.log(fieldCls.name);
//   new fieldCls()