When working with zod, you might have found yourself using .optional().nullable()
to make a field optional and nullable.
Especially when you are working with tRPC or similar API libraries, this is a common case for API input validation.
But there is a better way to do this.
Instead of using .optional().nullable()
, you can use .nullish()
.
const schema = z.object({
name: z.string().optional().nullable(), // ❌ don't do this
name: z.string().nullish(), // ✅ do this instead
});
Start your scalable and production-ready SaaS today
Save endless hours of development time and focus on what's important for your customers with our SaaS starter kits for Next.js, Nuxt 3 and SvelteKit
Get startedStay up to date
Sign up for our newsletter and we will keep you updated on everything going on with supastarter.