#Typescript typings for parent/child class methods

5 messages · Page 1 of 1 (latest)

dusk pier
#

I'm creating mini orm in my pet-project.
Trying to do models usable in IDE and compiler, but stuck with typing problems.I have base model class:
https://github.com/kricha/ts_q/blob/main/src/Models/BaseModel.ts
And child class:

import { BaseModel } from './BaseModel';
export class User extends BaseModel {
  static _table = 'users';

  static _pk = 'id';

  id: number;

  email: string;

  password: string;

  // eslint-disable-next-line @typescript-eslint/no-useless-constructor
  constructor(props: { id?: number; email: string; password: string }) {
    super(props);
  }
}

static method from base class works good, but after adding create method I'm getting error while compile... Errors described in comments in code.One more error could be achieved with code:

new User({ email: '[email protected]', password: '123123' }).create().then((user) => {//TS2684: The 'this' context of type 'User' is not assignable to method's 'this' of type 'typeof BaseModel'.   Type 'User' is missing the following properties from type 'typeof BaseModel': prototype, _pk, _table, findOne, and 2 more
  console.log(user);
});

Don't understand what I'm doing wrong, I do all in analogy with static method.Also full code for experiments available here - https://github.com/kricha/ts_q

GitHub

Contribute to kricha/ts_q development by creating an account on GitHub.

GitHub

Contribute to kricha/ts_q development by creating an account on GitHub.

dusk pier
#

any thoughts?

placid bison
#

seems like you're mixing up when you want to talk about the type of the static side of a class vs its instance type

#

the type named BaseModel represents instances of BaseModel (the value you get back after using new). typeof BaseModel is the type of the class object

#

so for example i suspect create is supposed to be:

create<T extends typeof BaseModel>(this: InstanceType<T>): Promise<InstanceType<T>>