Reputation: 9278
I want to have base model:
export class BaseModel<T> {
public static create(obj:any):T {
let instance = _.assignIn(new T(), obj);
return instance;
}
}
and then, specific model:
export class MyModel: BaseModel<MyModel> {
public prop1:string;
}
then, I want to create models in the following way:
let myModel = MyModel.create(...);
But, I can't force it work and get error:
'T' only refers to a type, but is being used as a value here.
Upvotes: 1
Views: 262
Reputation: 164129
You cannot use the generic constraint as a value, it does not exist in runtime, so this:
new T()
Makes no sense.
You can do this:
class BaseModel {
public static create<T extends BaseModel>(obj: any): T {
let instance = Object.assign(new this(), obj);
return instance;
}
}
Then
let myModel = MyModel.create<MyModel>(...);
Will work properly.
Upvotes: 4