網站搜尋

javascript - 我如何可以創建 Object?


我有一些問題:

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

在 TypeScript 中,泛型是透過類型擦除實現的,因此在執行時,T 對 JavaScript 類別而言是未知的。為了解決這個問題,你可以將建構子傳入 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);