objection.js
objection.js copied to clipboard
The `ModelObject<this>` type lose properties.
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"
Not really related to objection? Typescript seems to do it this way. ModelObject<User> works.
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;
}
}

Oh damn. Are you using typescript 4?
v4.0.3
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.
Experiencing this.
"typescript": "4.1.5" "objection": "2.2.14"