objection.js
objection.js copied to clipboard
Improve ModelObject type
Let's say there's a user model called User
:
class UserModel extends Model {
id!: number;
email?: string;
}
Now we want to add a new user with User.query().insert
method.
Let's define the parameter of insert
method as userToInsert
.
const userToInsert = { ... };
User.query().insert(userToInsert);
Objection provides (at least) two types that could be used for userToInsert
: PartialModelObject
and ModelObject
.
The problem with these types is that PartialModelObject
makes all properties optional where ModelObject
makes them required.
Wanted end result:
// ERROR!
const userToInsert = {}
// OK
const userToInsert = {
id: 1
}
// ERROR!
const userToInsert = {
email: '[email protected]'
}
I have created a new type ModelProperties<T>
that fixes the issue and works as above.
It could be a good idea to refactor objection
to use it instead of PartialModelObject
and ModelObject
. This way objections methods would also have stronger typings.
@AleksiVirkkala check this PR: https://github.com/Vincit/objection.js/pull/2276 I made it to solve this issue few months ago, not merged yet. WDYT ?
I suggest you to override the type in your project root if you want to solve it locally in your project.
Typing model fields as optional with ?:
might be questionable in the first place, but if I had to choose between this PR and https://github.com/Vincit/objection.js/pull/2276, I would go with the latter, since it's more straightforward.
Released in v3.0.5