Sub topic 7
Optional, nullable, and default fields
This chapter assumes you can define a z.object schema, call parse and safeParse, and derive a type with z.infer. It also assumes you know that TypeScript treats undefined and null as different types. Real data often leaves a field out, sends null, or sends nothing useful. Zod gives you a separate modifier for each case, and picking the wrong one is a common source of bugs.
Three kinds of "no value"
JavaScript has two empty values, and a missing key is a third situation.
- A missing key:
{ id: 1 }has nonicknameproperty at all. undefined:{ id: 1, nickname: undefined }has the property, but its value isundefined. JSON cannot express this, but in-memory objects can.null:{ id: 1, nickname: null }says explicitly that there is no value.
By default, a Zod schema accepts none of these. z.string() rejects undefined and null, and z.object rejects a missing required key. The modifiers below widen what a field accepts.
optional
.optional() accepts undefined, and so accepts a missing key too.
import { z } from "zod";
const Account = z.object({
id: z.number().int(),
nickname: z.string().optional(),
});
type Account = z.infer<typeof Account>;
// { id: number; nickname?: string | undefined }
console.log(Account.parse({ id: 1 })); // { id: 1 }
console.log(Account.parse({ id: 1, nickname: undefined })); // { id: 1, nickname: undefined }
console.log(Account.parse({ id: 1, nickname: "kit" })); // { id: 1, nickname: 'kit' }A missing key stays missing in the output. Zod does not add nickname: undefined for you.
.optional() does not accept null. Account.parse({ id: 1, nickname: null }) throws, because null is not a string and is not undefined.
nullable
.nullable() accepts null and nothing else extra. The key must still be present.
const Article = z.object({
title: z.string(),
publishedAt: z.string().nullable(),
});
type Article = z.infer<typeof Article>;
// { title: string; publishedAt: string | null }
Article.parse({ title: "Hi", publishedAt: null }); // ok
Article.parse({ title: "Hi" }); // throws: publishedAt is requiredUse nullable when the producer always sends the field and uses null to mean "empty". Databases and many JSON APIs work this way. The inferred type forces your code to handle null when it reads the field.
nullish
.nullish() is shorthand for .nullable().optional(). It accepts string, null, undefined, and a missing key. Use it when you consume an API that is inconsistent about whether it omits a field or sends null, and you want to tolerate both.
What each modifier accepts
| Schema | Value present | Key missing or `undefined` | `null` |
|---|---|---|---|
| `z.string()` | accepted | rejected | rejected |
| `z.string().optional()` | accepted | accepted | rejected |
| `z.string().nullable()` | accepted | rejected | accepted |
| `z.string().nullish()` | accepted | accepted | accepted |
| `z.string().default("x")` | accepted | replaced by `"x"` | rejected |
default
.default(value) supplies a fallback when the input is undefined. The output then always has a value, so the output type loses undefined.
const Settings = z.object({
theme: z.enum(["light", "dark"]).default("light"),
pageSize: z.number().int().positive().default(20),
});
type SettingsOut = z.output<typeof Settings>;
// { theme: "light" | "dark"; pageSize: number }
type SettingsIn = z.input<typeof Settings>;
// { theme?: "light" | "dark" | undefined; pageSize?: number | undefined }
console.log(Settings.parse({})); // { theme: 'light', pageSize: 20 }
console.log(Settings.parse({ theme: "dark" })); // { theme: 'dark', pageSize: 20 }The input type and output type differ here. A caller may omit theme, but your code reading the parsed result can rely on it. z.infer gives you the output type. Use z.input when you describe what callers may send. A later chapter covers this distinction in detail.
Computed defaults
Pass a function when the default must be computed each time, such as a timestamp or a fresh array. A plain value is shared across parses, so a fresh object per parse needs a function.
const Note = z.object({
text: z.string(),
createdAt: z.date().default(() => new Date()),
tags: z.array(z.string()).default(() => []),
});
const note = Note.parse({ text: "buy milk" });
console.log(note.tags.length); // 0
console.log(note.createdAt instanceof Date); // truedefault does not handle null
default fires only for undefined. A null input is not replaced.
To turn null into a fallback, accept it and then replace it:
const Author = z.object({
name: z
.string()
.nullish()
.transform((value) => value ?? "anonymous"),
});
console.log(Author.parse({ name: null })); // { name: 'anonymous' }
console.log(Author.parse({})); // { name: 'anonymous' }
console.log(Author.parse({ name: "Ada" })); // { name: 'Ada' }The output type of name is string. The input type is string | null | undefined.
Where checks run
Zod applies the default before the inner schema's checks in Zod 3, and in that version the default value is validated like any other input. Zod 4 returns the default as given and does not validate it. In both versions, write defaults that already satisfy the schema, because you then do not depend on the difference. TypeScript also checks the default against the output type.
Do not stack .default() and .optional() on the same field. The result depends on the order and the Zod version, and it is hard to read. If you want a fallback, use default alone. If you do not, use optional alone.
catch: a fallback for any failure
.catch(value) is different from default. It returns the fallback when parsing fails for any reason, not only when the input is undefined.
const Limit = z.number().int().min(1).catch(10);
console.log(Limit.parse(5)); // 5
console.log(Limit.parse("abc")); // 10
console.log(Limit.parse(undefined)); // 10
console.log(Limit.parse(-3)); // 10This hides bad input, so the caller never learns that anything was wrong. Reserve it for fields where a wrong value is truly harmless, such as a display preference read from storage. For anything that affects behavior, prefer default, which still rejects invalid values.
Optional versus nullable in a real payload
Consider a PATCH body for a user profile. A client may leave a field out to mean "do not change it" and send null to mean "clear it".
const ProfilePatch = z.object({
displayName: z.string().min(1).optional(),
bio: z.string().max(280).nullable().optional(),
});
type ProfilePatch = z.infer<typeof ProfilePatch>;
// { displayName?: string | undefined; bio?: string | null | undefined }
function applyPatch(current: { displayName: string; bio: string | null }, raw: unknown) {
const patch = ProfilePatch.parse(raw);
return {
displayName: patch.displayName ?? current.displayName,
bio: patch.bio === undefined ? current.bio : patch.bio,
};
}
const before = { displayName: "Ada", bio: "Hello" };
console.log(applyPatch(before, {})); // { displayName: 'Ada', bio: 'Hello' }
console.log(applyPatch(before, { bio: null })); // { displayName: 'Ada', bio: null }Here undefined and null carry different meanings, so collapsing them with ?? on bio would be a bug. When the two states mean different things, keep the distinction. When they mean the same thing, normalize early so the rest of the code deals with one empty value.
Common errors
- Using
optionalfor a field that arrives asnull. The parse fails at that path. Check the producer's actual output and usenullableornullish. - Expecting
defaultto replacenullor an empty string. It replaces onlyundefined. HTML forms send""for empty text inputs, so convert empty strings with a transform or a preprocessing step before relying on a default. - Reading
z.inferwhen you need the input type. For a schema with defaults,z.infershows required fields that callers may omit. Usez.inputfor function parameters that accept raw data. - Using
catchwheredefaultis intended.catchsilently accepts malformed values. - Making everything
nullish"to be safe". A loose schema pushesnullandundefinedchecks into every consumer. Be as strict as the data source allows.
Exercise
Write a schema for { port, host, tls } where port is a positive integer that defaults to 8080, host is a required string, and tls is a boolean that may be absent or null, where either means false in the output. What are the output types of the three fields?
Show answer
const Config = z.object({ port: z.number().int().positive().default(8080), host: z.string(), tls: z.boolean().nullish().transform((v) => v ?? false) }); The output types are port: number, host: string, tls: boolean. The input type of tls is boolean | null | undefined.
Exercise
Given z.string().default("n/a"), what does parsing undefined, null, and "" produce?
Show answer
undefined produces "n/a". null fails with a validation issue because default replaces only undefined and the schema is not nullable. "" passes and stays "" because an empty string is a valid string.