3

i have some problem:

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

String "const model = new T(object)" have error:

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

Anyone know how i can create new T?

1 Answers1

1

In typescript generic are implemented using type erasure, so at runtime the T will not be known to the Javascript class. To get around this you can pass in the constructor to the T type as a parameter to the Collection constructor

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);
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357