user348173
user348173

Reputation: 9278

Create instances from static method of generic class

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

Answers (1)

Nitzan Tomer
Nitzan Tomer

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

(code in playground)

Then

let myModel = MyModel.create<MyModel>(...);

Will work properly.

Upvotes: 4

Related Questions