[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:
const users = mysqlTable("users", {
...
speciality: varchar('speciality', { length: 255 }),
level: tinyint('level'),
...
});
const users = mysqlTable("users", {
...
speciality: varchar('speciality', { length: 255 }),
level: tinyint('level'),
...
});
The generated schema will have this type
type Schema = {
speciality: string | null | undefined,
level: number | null | undefined
}
type Schema = {
speciality: string | null | undefined,
level: number | null | undefined
}
Is there a way to make it like this ?
type Schema = {
speciality: string ,
level: number
}
type Schema = {
speciality: string ,
level: number
}
9 Replies
Ahmed
AhmedOP15mo ago
up
rphlmr ⚡
rphlmr ⚡15mo ago
can you try to add .required() at the end of your generated Zod schema? Reference: https://github.com/colinhacks/zod#required
Angelelz
Angelelz15mo ago
I think you only need to add notNull() to the columns that you want to be required. Like so:
const users = mysqlTable("users", {
...
speciality: varchar('speciality', { length: 255 }).notNull(),
level: tinyint('level').notNull(),
...
});
const users = mysqlTable("users", {
...
speciality: varchar('speciality', { length: 255 }).notNull(),
level: tinyint('level').notNull(),
...
});
Ahmed
AhmedOP15mo ago
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.
rphlmr ⚡
rphlmr ⚡15mo ago
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
Ahmed
AhmedOP15mo ago
Thanks!, For zod I think I have to transform the properties to remove the nullability 🙂
Angelelz
Angelelz15mo ago
Do you have strict mode not enabled? That might be messing with your types.
Ahmed
AhmedOP15mo ago
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.
// Refining the fields - useful if you want to change the fields before they become nullable/optional in the final schema
// Refining the fields - useful if you want to change the fields before they become nullable/optional in the final schema
Angelelz
Angelelz15mo ago
Silly me, I didn't noticed you were asking about drizzle-zod. My bad.
Want results from more Discord servers?
Add your server