Nullable API fields
An API field may explicitly contain null while retaining validation for non-null values.
Zod · Function
z.nullable wraps a schema to accept its usual values plus null. It is equivalent to calling .nullable() on the inner schema.
z.nullable wraps an existing schema so that the resulting schema accepts values valid for the inner schema as well as null. The equivalent method form is innerSchema.nullable(), and the wrapped schema can be retrieved with unwrap().
z.nullable(innerType)| Name | Type | Description |
|---|---|---|
innerType | ZodType | The schema whose valid values should also allow null. |
A nullable schema that accepts values valid for the inner schema or null.
import { z } from "zod";
const nullableString = z.nullable(z.string());
console.log(nullableString.parse("hello")); // "hello"
console.log(nullableString.parse(null)); // nullCreates a schema that accepts either a string or null and validates both inputs.
An API field may explicitly contain null while retaining validation for non-null values.
A form or database value is either a validated value or an intentional null.
A schema is assembled from reusable validators and nullability is added at construction time.
It wraps an inner schema and extends its accepted values with null. For example, z.nullable(z.string()) accepts either a string or null.
Follow-up: How would you express the same schema using method syntax? Use z.string().nullable(), which is equivalent to z.nullable(z.string()).
The inner schema remains responsible for validating non-null values, while null is accepted directly. The inferred TypeScript type for a nullable string is string | null.
Follow-up: How can you recover the original schema? Call unwrap() on the nullable schema; it returns the inner schema.
Use z.nullable(innerSchema) when constructing a nullable schema, or innerSchema.nullable() as the convenience form. Both produce equivalent validation behavior.
Follow-up: What is the distinction from nullish? Nullish permits both undefined and null, whereas nullable permits null in addition to the inner schema's values.
.nullable()z.nullish()z.null()unwrap()ZodNullable