Course contentsShow
← TypeScript
Lesson 1289 of 1,79630. Type-Safe APIsFree lesson

Optional and Nullable Fields

Use .optional() and .nullable() to handle fields that may be absent or explicitly null.

Optional and Nullable Fields

What you'll learn: How to use .optional() and .nullable() in Zod to handle API fields that might be missing or explicitly set to null.

The Two Flavors of "Not There"

In JSON APIs, a field can be absent in two different ways:

  1. Optional - The property key doesn't exist at all: { name: "Alice" } (no age field)
  2. Nullable - The property exists but its value is null: { name: "Alice", age: null }

These are different situations! An optional field means "this might not be sent," while a nullable field means "this is sent, but the value is explicitly nothing."

Using .optional() for Missing Fields

When a field might not exist in the response at all:

import { z } from 'zod';

const userSchema = z.object({
  name: z.string(),
  age: z.number().optional()
});

type User = z.infer<typeof userSchema>;
// { name: string; age?: number | undefined }

This validates both { name: "Bob", age: 30 } and { name: "Bob" }, but rejects { name: "Bob", age: null }.

Using .nullable() for Explicit Null

When a field exists but can be null:

const profileSchema = z.object({
  bio: z.string().nullable()
});

type Profile = z.infer<typeof profileSchema>;
// { bio: string | null }

This requires the bio key to exist, accepts { bio: "Hello" } and { bio: null }, but rejects { bio: undefined } or missing bio entirely.

Combining Both: .optional().nullable()

For fields that might be missing or null (common in real APIs):

const apiResponseSchema = z.object({
  description: z.string().optional().nullable()
});

type ApiResponse = z.infer<typeof apiResponseSchema>;
// { description?: string | null | undefined }

This accepts all of: {}, { description: "text" }, { description: null }, and { description: undefined }.

Key Takeaway: Use .optional() when fields might be absent from the object, .nullable() when they're present but can be null, and chain both when either situation is valid—matching your API's actual behavior precisely.