ModelObject type maps optional properties as required
See original GitHub issueGreetings,
I’m using objection@2.2.3
and typescript@4.0.2
.
Let’s say that I have a simple class like this:
class PersonModel extends Model {
id: string;
name: string;
phone?: number;
}
When I use ModelObject<PersonModel>
to create a POJO
typing of this class, it gives me this result:
type PersonPojo = {
id: string;
name: string;
phone: number | undefined;
}
As you can see, phone
is an optional property in PersonModel
class. ModelObject
maps it to undefined
too, but makes it an required property.
I’m using graphql-codegen
and to map the typings of the generated response types to my classes, I use ModelObject
.
Because of it maps these kind of properties as required, if you have lots of relationships under PersonModel
, it wants you to set all of those properties (as undefined
or its own value type).
To not miss which properties are optional, I’ve modified ModelObject
like this:
type ModelObject2<T extends Model> = Pick<
T,
Exclude<NonFunctionPropertyNames<T>, 'QueryBuilderType'>
>;
And when I use ModelObject2<PersonModel>
, it protects the optional properties like this:
type PersonPojo = {
id: string;
name: string;
phone?: number | undefined;
}
I’m not sure if this is an expected behavior of ModelObject
but wanted to give a heads up about this.
Mine can be an edge case which may require a custom solution like ModelObject2
of course.
But other people may bump into this kind of an issue too.
Thanks for this great package!
Issue Analytics
- State:
- Created 3 years ago
- Reactions:4
- Comments:7
Tested w/ Typescript 4.5.5
Same problem here. Thanks for the workaround @onderonur !