Skip to content

Conversation

@AleksiVirkkala
Copy link

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: 'example@email.com'
}

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.

@flodlc
Copy link
Contributor

flodlc commented Aug 16, 2022

@AleksiVirkkala check this PR:
#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.

@lehni lehni self-assigned this Apr 14, 2023
@lehni lehni added the typings label Apr 15, 2023
*/
type KeysWithFunctionType<T> = {
[K in keyof T]: T[K] extends Function ? K : never;
}[keyof T];
Copy link
Collaborator

@lehni lehni Apr 16, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the reverse of the already existing NonFunctionPropertyNames, I think the name should reflect that:

FunctionPropertyNames

@falkenhawk
Copy link
Contributor

Typing model fields as optional with ?: might be questionable in the first place, but if I had to choose between this PR and #2276, I would go with the latter, since it's more straightforward.

@lehni
Copy link
Collaborator

lehni commented Jul 20, 2023

Released in v3.0.5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

4 participants