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

Improve ModelObject type

Open AleksiVirkkala opened this issue 2 years ago • 1 comments

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 avatar Jul 12 '22 08:07 AleksiVirkkala

@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.

flodlc avatar Aug 16 '22 16:08 flodlc

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.

falkenhawk avatar Apr 17 '23 15:04 falkenhawk

Released in v3.0.5

lehni avatar Jul 20 '23 11:07 lehni