Home > OS >  Express Typescript Objection pass model to super class using generic type not working
Express Typescript Objection pass model to super class using generic type not working

Time:06-23

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

CodePudding user response:

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();
  • Related