我如何创建Object <t>?

时间:2017-09-13 07:18:36

标签: javascript typescript ecmascript-6

我有一些问题:

class Collection<T extends IModel> extends Event implements ICollection<T> {
   constructor(array: any[] = []) {        
    super()
    this._init(array)
   }
   private _init(array: any[]) {
    array.forEach((object) => {
     if (this._isModel(object)) {
       return console.log("hey")
     }
     const model = new T(object)
    })
}

字符串“const model = new T(object)”有错误:

error TS2693: 'T' only refers to a type, but is being used as a value here.

任何人都知道如何创建新的T?

1 个答案:

答案 0 :(得分:1)

在typescript中,泛型是使用类型擦除实现的,因此在运行时,Javascript类不会知道T.要解决此问题,您可以将构造函数传递给T类型作为Collection构造函数的参数

class Collection<T extends IModel> extends Event implements ICollection<T> {
    constructor(array: any[] = [], public ctor: new (data: any[]) => T) {        
     super()
     this._init(array)
    }
    private _init(array: any[]) {
     array.forEach((object) => {
      if (this._isModel(object)) {
        return console.log("hey")
      }
      const model = new this.ctor(object)
     })
 }
}
class Model{
   constructor(public object: any[]  ){}
}

let data = new Collection<Model>([], Model);