objection.js icon indicating copy to clipboard operation
objection.js copied to clipboard

The `ModelObject<this>` type lose properties.

Open sanonz opened this issue 5 years ago • 6 comments

type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];

type ModelObject<T extends object> = {
  [K in Exclude<NonFunctionPropertyNames<T>, 'model'>]: T[K];
};

class User {
  id!: number;
  name!: string;
  avatar!: string;

  toJson () {
    const rs: ModelObject<this> = 0 as any;

    return rs;
  }

  getName () {
    const json = this.toJson();

    return json.name; // Property 'name' does not exist on type 'ModelObject<this>'.
  }
}

type UserJson = NonFunctionPropertyNames<User>; // output type UserJson = "id" | "name" | "avatar"

sanonz avatar Sep 25 '20 03:09 sanonz

Not really related to objection? Typescript seems to do it this way. ModelObject<User> works.

koskimas avatar Sep 25 '20 07:09 koskimas

I mean overwriting the $toJson method is an error for the typescript.

import { Model } from 'objection';

export default class User extends Model {
  id!: number;
  name!: string;
  avatar!: string;

  $toJson () {
    const json = super.$toJson();

    json.avatar = 'http://domain.com/' + json.avatar;

    return json;
  }
}

image

sanonz avatar Sep 25 '20 08:09 sanonz

Oh damn. Are you using typescript 4?

koskimas avatar Sep 25 '20 11:09 koskimas

v4.0.3

sanonz avatar Sep 25 '20 11:09 sanonz

Ok. I think this is a bug introduced by typescript 4. Objection's tests still use 3.9.something. Typescrip 4 probably changed how the this type is handled in some cases.

koskimas avatar Sep 25 '20 13:09 koskimas

Experiencing this.

"typescript": "4.1.5" "objection": "2.2.14"

cerinoligutom avatar Feb 20 '21 15:02 cerinoligutom