2017-09-13 101 views
2

我有一些问题:我如何创建对象<T>?

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

字符串 “常量模式=新T(对象)” 有错误:

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

任何人都知道我可以创建新型T?

+0

你可以写常量模型=新的对象(); –

回答

1

在typescript generic中使用类型擦除来实现,所以在运行时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);