代码之家  ›  专栏  ›  技术社区  ›  unloco

实例化接口类型的变量

  •  0
  • unloco  · 技术社区  · 6 年前

    我想在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 回复  |  直到 6 年前
        1
  •  2
  •   Matt McCutchen    6 年前

    的属性类型 fields IHtmlField 实例,但构造 伊赫特姆菲尔德 :

    const fields: {[type: string]: {new(): IHtmlField}} = {
      text: TextInput,
      file: FileInput
    }
    
        2
  •  0
  •   vich    6 年前

    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()