Search code examples
node.jstypescriptknex.jsobjection.js

Express + Typescript + Objection pass model to super class using generic type not working


class BaseService<Models> {
  
  public m: Models;

  constructor(model: Models) {
    this.m = model;
  }
}


class MyService extends BaseService<UserModel>{
  
  constructor() {
    super(UserModel);  //It is require new keyword
  }

}

We are using knex.js with Objection.js models. I'm able to run queries in MyService class. e.g.

const user = await UserModel.query().findById(1);

But instead i want a base service that to set Model using generic type.

What i need from child class id.

super(UserModel);  //It is not working

If i pass UserModel using new keyword then error removed but queries not working

super(new UserModel())

Solution

  • Typescript Playground Link

    You tried to pass class to super class, but it expected instance of that class

    class BaseService<Models> {
      
      public m: Models;
    
      constructor(model: Models) {
        this.m = model;
      }
    }
    
    class UserModel {}
    
    class MyService extends BaseService<typeof UserModel>{
      
      constructor() {
        super(UserModel);  //It is require new keyword
      }
    
    }
    
    new MyService();