javascript - 我如何创建对象 <T>?

标签 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 吗?

最佳答案

在 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);

关于javascript - 我如何创建对象 <T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46191227/

相关文章:

javascript - 将数字数组转换为合适的正则表达式

angular - 如何在所有验证通过之前阻止表单提交 [Angular 7]

arrays - Angular 6 : retrieve data from SelectionModel

javascript - let 变量等于 var 变量吗?

javascript - 如何保留对象的某些属性?

javascript - vue-material:未知的自定义组件 md-drawer & md-content

javascript - JavaScript import 如何找到没有扩展名的模块?

angular - RxJS 'Map' 运算符在 Angular 6 中不起作用

javascript - 由于缺少 &lt;script&gt;,无法看到“关于”页面路由,但能够到达“主页”路由

javascript - 如何在每次更改时从 jquery slider 获取值?