Partial Updates with .nullish() and Object Spread

May 5, 2025

When building APIs, it’s common to allow partial updates—where only some fields are changed, and others are left untouched. In TypeScript, especially when using Zod for validation and Drizzle or Prisma for database updates, there’s a neat pattern that makes this both explicit and type-safe.

The Power of .nullish()

Zod’s .nullish() method allows a field to be undefined or null. This distinction is powerful:

  • undefined means “don’t touch this field.”
  • null means “explicitly set this field to null in the database.”

This gives your API consumers fine-grained control over what gets updated and what doesn’t.

Clean Updates with Object Spread

Instead of building up an update object with a bunch of conditionals, you can use object spread syntax:

.set({
  ...(input.userUploadId !== undefined ? { userUploadId: input.userUploadId } : {}),
  ...(input.invoiceAmount !== undefined ? { invoiceAmount: input.invoiceAmount } : {}),
  ...(input.description !== undefined ? { description: input.description } : {}),
})

This pattern ensures that only the fields provided (even if explicitly null) are included in the update, and everything else is left untouched.

  • Explicitness: Callers can choose to update, clear, or ignore each field.
  • Simplicity: No more manual object construction or type assertions.
  • Type Safety: Works seamlessly with Zod and TypeScript.

If you’re building APIs with TypeScript, give this pattern a try—it’s clean, expressive, and robust.