[drizzle-zod] How to make all fields of a schema derived from a table required ?
I just tried the plugin and I'm happy to move from manually creating zod schemas.
However, I came into a use case where a schema must have all nullable fields in the table required.
Assume we have these in users table:
The generated schema will have this type
Is there a way to make it like this ?
9 Replies
up
can you try to add
.required()
at the end of your generated Zod schema?
Reference: https://github.com/colinhacks/zod#requiredI think you only need to add
notNull()
to the columns that you want to be required.
Like so:
It removes the
undefined
type only while null
remains.
The fields can be null in the database according to the requirements.
But what I mean is when using the schema in a form that requires the user to fill so that I update the table according to the form. I'm 100% assured that I will receive these fields from the form.Typescript side, you can wrap the inferred type with
NonNullable<MyInferredType>
(https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullabletype) but I fear it'll be impossible to manage that in the zod schema.Documentation - Utility Types
Types which are globally included in TypeScript
Thanks!,
For zod I think I have to transform the properties to remove the nullability 🙂
Do you have strict mode not enabled? That might be messing with your types.
Strict mode is always enabled
I'm inferring the type from parsing a zod schema
This is what
drizzle-zod
do before creating the schema.
Silly me, I didn't noticed you were asking about drizzle-zod. My bad.