1

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.

3
  • 2
    Possible duplicate of Typescript instantiate generic object Commented May 10, 2017 at 21:31
  • My case is different. Commented May 10, 2017 at 21:34
  • 1
    The solution is the same - add another parameter to create. Define it like create(cls: {new(): T}, obj: any) { ... assignIn(new cls(), obj); ...}, use it like MyModel.create(MyModel, ...). Commented May 10, 2017 at 21:38

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.