Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

API reference

Zod API reference

Zod schema validation

Identifiers
123
With full guides
76
Types
4

Topics covered

  • Basic schemas
  • Objects & arrays
  • Refinements
  • Transforms
  • Infer types
  • Discriminated unions
  • Error handling
  • Coercion

Function

NameWhat it does
z.objectFunction
z.stringz.string() creates a Zod schema for validating strings. Chain its string-specific checks and transformations, then parse input with parse or safeParse.
z.numberz.number() creates a Zod schema for finite numeric values. Chain numeric checks such as bounds, positivity, and divisibility to express stricter requirements.
z.arrayz.array creates a schema for arrays whose elements conform to a supplied Zod schema. It also supports array-length constraints and readonly output types.
z.enumFunction
z.unionFunction
z.discriminatedUnionFunction
parseValidates unknown input against a Zod schema. It returns a strongly typed deep clone on success and throws a ZodError on failure.
safeParsesafeParse validates data without throwing on validation failure. It returns either parsed data on success or a ZodError on failure, distinguished by the result's success field.
refineFunction
transformz.transform() creates a unidirectional Zod schema that accepts any input and maps it to a new output through a callback. Use it with pipes when validation must precede transformation.
z.booleanz.boolean() creates a Zod schema for validating boolean values. It accepts true and false; use z.coerce.boolean() when JavaScript-style coercion is desired.
z.datez.date() creates a Zod schema for validating JavaScript Date instances. Add min() and max() to enforce lower and upper date boundaries.
z.literalz.literal(value) validates one exact literal value, such as a string, number, bigint, or boolean. The resulting schema infers the corresponding TypeScript literal type and rejects other values.
z.optionalFunction
z.nullablez.nullable wraps a schema to accept its usual values plus null. It is equivalent to calling .nullable() on the inner schema.
z.recordCreates a schema for dictionary-like objects with dynamic keys. It validates each key with one schema and each value with another, producing a corresponding TypeScript Record type.
z.tuplez.tuple defines a tuple schema whose positions can use different Zod schemas. An optional rest schema allows additional values after the fixed prefix.
z.intersectionCombines two Zod schemas with logical AND semantics. The input must satisfy both schemas, and the inferred type is their intersection.
z.lazyFunction
z.customz.custom() creates a Zod schema for a TypeScript type that lacks a built-in Zod schema. Supply a predicate for runtime validation and an optional custom error message; without a predicate, it accepts any value.
z.brand.brand() adds a compile-time marker to a Zod schema’s inferred type, separating validated values from ordinary structurally similar values. It is static-only and does not change parsed runtime values.

Type Alias

NameWhat it does
z.inferz.infer extracts a static TypeScript type from a Zod schema. Use z.infer<typeof schema> to create a reusable alias that reflects the schema, including its output type when transformations are present.
ZodTypeType Alias
ZodSchemaType Alias
ZodErrorType Alias
ZodIssueType Alias
ZodObjectType Alias
ZodStringType Alias
ZodNumberZodNumber is the schema type created by z.number(). It validates finite JavaScript numbers and supports additional numeric constraints such as bounds, integer checks, signs, and multiples.
ZodArrayZodArray is the schema type created for arrays with z.array(elementSchema) or elementSchema.array(). It validates each item and supports array length constraints such as nonempty, min, max, and length.
ZodEnumType Alias
ZodUnionZodUnion is Zod’s schema type for logical OR validation. It accepts an input when any member schema succeeds, testing members in order and returning the first successful parsed value.
ZodEffectsType Alias
RefinementCtxRefinementCtx is the context passed to custom refinement callbacks. Use it to record validation issues and associate them with locations in the parsed data.
SafeParseReturnTypeType Alias
ZodTypeAnyType Alias
ZodRawShapeZodRawShape is the object-like map of property names to Zod schemas used to define Zod object fields. Use it directly as a reusable shape or pass it to z.object to create an object schema.
inferz.infer derives a static TypeScript type from a Zod schema. Use z.infer<typeof schema> to create a reusable type alias that stays aligned with the schema definition.
inputz.input extracts the TypeScript input type of a Zod schema. It is useful when a schema’s accepted input differs from its parsed output, such as with coercion or preprocessing.
outputz.output<typeof schema> extracts the TypeScript type produced by a Zod schema. It is especially useful when parsing transforms the input into a different output type.
TypeOfType Alias

Const

NameWhat it does
z.coercez.coerce provides primitive schemas that first convert unknown input with JavaScript constructors, then validate the converted value. Documented variants cover strings, numbers, booleans, and bigints.

Module

NameWhat it does
z.bigintz.bigint() creates a Zod schema for validating JavaScript bigint values. It supports comparison, sign, and divisibility constraints.
z.symbolz.symbol() creates a Zod schema for JavaScript symbols. It validates symbol values at runtime and can also be used alongside symbol-keyed object properties.
z.undefinedModule
z.nullz.null() creates a Zod schema that accepts exactly the JavaScript value null. Use z.nullable() or z.nullish() when null should be combined with other accepted values.
z.voidModule
z.anyz.any() defines a schema that accepts values of any type and infers any in TypeScript. As an object property, it requires the key unless combined with .optional().
z.unknownz.unknown() defines a schema that accepts any runtime value while inferring TypeScript’s safer unknown type. Use it when input shape is intentionally unrestricted but downstream code must narrow the value before using it.
z.neverz.never() creates a Zod schema that rejects every input and infers the TypeScript type never. Use it to model an impossible schema branch.
z.nanz.nan() creates a schema that accepts JavaScript’s NaN value and rejects all other inputs. Use it when NaN must be validated explicitly rather than treated as an ordinary number.
z.mapz.map() creates a Zod schema for JavaScript Maps by defining separate schemas for keys and values. It infers the corresponding TypeScript Map type and supports entry-count and readonly constraints.
z.setz.set(element) creates a Zod schema for native JavaScript Set values, validating each member with the supplied element schema. Set schemas support cardinality constraints such as nonempty, min, max, and size.
z.functionModule
z.promiseModule
z.nativeEnumModule
z.default.default() supplies a fallback when a schema receives undefined. It returns that fallback immediately and can also generate defaults through a function.
z.catch.catch() supplies a fallback when schema validation fails. The fallback can be a fixed value or a function that is rerun for each failure and receives the caught error context.
z.preprocessz.preprocess() transforms raw input before passing it to another Zod schema for validation. It is useful for custom normalization or coercion, while straightforward primitive coercion can use Zod's dedicated coercion APIs.
z.instanceofz.instanceof(Class) validates that an input is an instance of a specified class. Successful parsing preserves the original object, including its prototype and identity.
z.pipez.pipe() composes schemas into a sequential pipeline. It is especially useful for validating data before a transform and validating or processing the transformed result.
z.transformz.transform() creates a standalone, unidirectional schema that accepts any input and maps it to a new output. Use it with z.pipe() or .transform() when input validation should precede the conversion.
.minModule
.max.max() adds an inclusive upper bound to a Zod schema. Its meaning depends on the schema: string length, array item count, file size, or a comparable maximum for dates and bigints.
.length.length(n) requires a string or array to have exactly n units according to Zod’s counting rules. Strings are measured in Unicode code points; arrays are measured by item count.
.emailz.email() creates a schema for validating email addresses. It uses a comparatively strict default pattern and accepts a custom pattern regular expression for alternative rules.
.urlz.url() validates WHATWG-compatible URL strings. Optional protocol and hostname regular expressions let you narrow the accepted URLs.
.uuidz.uuid() creates a Zod schema for validating RFC 9562/4122-compliant UUID strings. It can restrict validation to a specified UUID version, while z.guid() handles less strict UUID-like identifiers.
.cuidModule
.cuid2Module
.ulidModule
.regexModule
.startsWithModule
.endsWithModule
.includesModule
.trimz.string().trim() creates a string schema that removes surrounding whitespace from parsed values. It is a built-in string transformation that can be chained with other string checks and transforms.
.toLowerCase.toLowerCase() defines a Zod string schema that converts parsed strings to lowercase. It is a chainable string transformation.
.toUpperCase.toUpperCase() transforms parsed strings to uppercase. It takes no arguments and can be chained with other string transformations such as .trim().
.datetimez.iso.datetime() validates strings against a strict subset of ISO 8601. Timezone offsets are rejected by default and can be enabled with { offset: true }.
.ipZod provides separate schemas for IPv4 and IPv6 addresses. Use z.union() to accept either format.
.emojiz.emoji() validates a single emoji character in current Zod. It accepts complete emoji, including keycap sequences, while rejecting component-only strings such as 123.
.nanoidz.nanoid() creates a Zod schema for validating Nano ID strings. Use it wherever a schema is needed, including object fields and collections.
.base64Module
.gtModule
.gte.gte(value) adds an inclusive minimum constraint to a Zod number schema. Inputs below the supplied threshold fail validation, while the threshold and larger values are accepted.
.ltz.number().lt(value) validates finite numbers that are strictly less than value. It adds an exclusive upper bound to a Zod number schema.
.lteModule
.intz.int() defines a Zod schema for safe JavaScript integers. It accepts integer numbers within the safe range and rejects fractional, non-number, or unsafe values.
.positiveModule
.negativeModule
.nonnegativeModule
.multipleOf.multipleOf(value) constrains a Zod number to values that are multiples of value. Zod documents .step(value) as an alias.
.finiteModule
.safe.safeParse validates input and returns a result object instead of throwing on validation failure. Check success to access either parsed data or a ZodError.
.parse.parse validates an unknown value against a Zod schema. It returns a strongly typed deep clone on success and throws a ZodError on failure.
.safeParseZod's safeParse method validates input without throwing for validation failures. It returns a discriminated result containing either parsed data or a ZodError.
.parseAsyncModule
.safeParseAsyncModule
.partial.partial() derives a Zod object schema with optional properties. Use it without arguments for all fields, or provide a mask to make only selected fields optional.
.deepPartialz.deepPartial() recursively makes properties optional throughout a Zod schema. Unlike .partial(), it can traverse nested structures such as objects, arrays, tuples, unions, records, and wrappers.
.pick.pick derives a new Zod object schema containing only selected properties from an existing object schema. Provide a mask with the keys to retain set to true.
.omit.omit() derives a Zod object schema without selected keys. Pass a mask with the keys to remove set to true.
.extend.extend() creates a new object schema by adding fields to an existing object schema. Duplicate keys are overwritten by the supplied shape.
.mergeModule
.passthroughModule
.strictModule
.stripModule
.shape.shape exposes the individual field schemas inside a Zod object schema. Use it to retrieve a validator for a specific key, such as Dog.shape.name.
.keyofModule
.array.array() turns an existing Zod schema into an array schema, so each item is validated against that schema. Use array length methods such as .min(), .max(), .length(), and .nonempty() for collection constraints.
.orModule
.andModule
.nullish.nullish() makes a Zod schema accept its normal values plus null and undefined. It combines nullable and optional behavior.
.describe.describe() registers a schema description in Zod's global registry and returns a new schema instance. Zod recommends .meta() for new metadata because it supports the broader metadata API.
.refine.refine() adds custom validation to any Zod schema. Its predicate passes on truthy results and reports a custom issue on falsy results, with optional error and continuation settings.
.superRefine.superRefine() adds custom validation logic to a schema and can report multiple issues. It also supports Zod's internal issue types, unlike the single custom issue produced by .refine().
.readonly.readonly() marks a schema’s inferred output as readonly and freezes the parsed result at runtime. It supports objects, arrays, tuples, Set, and Map.
z.filez.file() creates a schema for validating File instances. Add byte-size limits with .min() and .max(), and restrict accepted content types with .mime().
z.stringboolz.stringbool() parses supported boolean-like strings into plain booleans. It is useful for text-based inputs such as environment variables and can encode booleans back to strings.
z.iso.datetimez.iso.datetime() validates strings against a strict subset of ISO 8601. By default it accepts UTC-style datetimes, rejects timezone offsets and local datetimes, and can allow offsets with { offset: true }.
z.iso.datez.iso.date() validates strings in the YYYY-MM-DD format and rejects malformed or impossible calendar dates. Use z.date() for JavaScript Date instances.
z.templateLiteralz.templateLiteral creates a Zod schema for strings formed by concatenating literal text and compatible schemas. It validates the complete assembled value and infers a corresponding TypeScript template-literal type.

Search across every package and filter by type in your dashboard.

Start learning