skip to content

Zod

Zod schemas validate unknown input at runtime and give the static TypeScript type from the same definition. Interviewers ask how you know a request body or API response really matches its type.

on this pageshow

explore

questions

page 1 of 2

In Zod 4, what does the ZodError from a failed safeParse contain, and what do each issue's code, path and message tell you?

level: juniorimportance: must knowfreq 62%

answer

  1. an array, not one sentence
  2. machine field plus human field
  3. keys and indexes from the root
  4. extra fields depend on the code
  5. raw value left out by default

basics

~20 s

A Zod 4 ZodError holds an issues array, one entry per problem. Each issue carries a code naming the kind of failure, a path locating the bad value from the root, a human message, and code-specific fields such as expected or minimum.

solid answer

~50 s

`safeParse` returns `{ success: false, error }`, and `error.issues` lists every problem Zod found across the input, not just the first. Each issue has a `code` such as `invalid_type`, `too_small`, `invalid_format` or `unrecognized_keys`; a `path` of keys and array indexes from the root, so `['items', 3, 'qty']` points at one nested value and `[]` means the input as a whole; and a `message`, which the default English locale writes for you, for example "Invalid input: expected string, received undefined" for a missing field. Code-specific fields carry the parameters: `expected` on `invalid_type`; `origin`, `minimum` and `inclusive` on `too_small`; `keys` on `unrecognized_keys`. The raw input is left out by default so that logging issues does not echo submitted values; pass `reportInput: true` to the parse call to include it. Program logic should branch on `code` and the parameters, and people should see `message`.

code

typescript · 13 lines
typescript
import * as z from "zod";

const SignUp = z.object({
  email: z.string(),
  password: z.string().min(8),
});

const result = SignUp.safeParse({ password: "short" });
if (!result.success) {
  for (const issue of result.error.issues) {
    console.log(issue.code, issue.path, issue.message);
  }
}

go deeper

for a junior

Recall that a failed parse gives an issues array, and name code, path and message, with path being an array of keys and indexes from the root.

for a middle

Explain the code-specific fields such as expected, minimum and keys, why a missing field shows up as invalid_type, and that input is dropped unless reportInput is set.

for a senior

Show that you branch on code and parameters rather than message text, and that you keep reportInput out of production logging because issues would then carry raw request values.

for a principal

Treat the issue list as the contract between validation and every consumer: forms, logs and translations all derive from code, path and parameters, so a team standardises on reading those.

## What a failed parse hands you Zod validates **unknown** input against a schema. When you call `safeParse`, you get back a result object: either `{ success: true, data }` with the typed value, or `{ success: false, error }`. The `error` is a **ZodError**, and its useful content is one property: `issues`, an array with one object per problem. Zod keeps validating after the first failure wherever it can. An object schema checks every declared field, so a sign-up body with a missing email and a short password produces two issues, not one. (Inside a single field, a value of the wrong type stops there: Zod does not run `.min()` on a number that was supposed to be a string.) ## The fields every issue carries | Field | What it holds | Who reads it | |---|---|---| | `code` | the kind of failure, as a fixed string | your program | | `path` | an array of object keys and array indexes from the root | your program, to place the error | | `message` | a human-readable sentence | people | | code-specific fields | the parameters of the failed rule | your program, translations | - **`code`** is the stable, machine-readable part. Branch on it, never on the message text. - **`path`** is an array, not a dotted string. `['address', 'zip']` is a nested field; `['phones', 1]` is the second element of an array, because indexes start at zero; `[]` means the problem is with the input as a whole. - **`message`** comes from the error map chain. With no customisation, the English locale that the `zod` package loads writes it, for example `Too small: expected string to have >=8 characters`. ## The issue codes in Zod 4 Zod 4 has eleven issue codes. The common ones: | Code | Raised when | Extra fields | |---|---|---| | `invalid_type` | the value is the wrong JavaScript type, including a missing required key | `expected` | | `too_small` / `too_big` | a length, size or numeric bound fails | `origin`, `minimum` or `maximum`, `inclusive`, sometimes `exact` | | `invalid_format` | a string format such as an email or UUID fails | `format`, sometimes `pattern` | | `invalid_value` | a literal or enum gets a value outside its set | `values` | | `unrecognized_keys` | a strict object meets keys it does not declare | `keys` | | `invalid_union` | no union option matched | `errors` (one issue list per option) | | `custom` | a refinement failed | `params`, if given | The rest are `not_multiple_of`, `invalid_key` and `invalid_element` (for record, map and set keys and members). Notice what is missing: there is **no `required` code**. A required key that is absent reaches its field schema as `undefined`, so it fails as `invalid_type`, and the English message ends with `received undefined`. ## The input is excluded by default Each issue is created with the failing input attached, so error maps can look at it. When Zod finalises the issue, it **drops `input`** unless the parse call asked for it: ```ts schema.safeParse(body, { reportInput: true }); ``` The default exists so that logging a ZodError does not write passwords, tokens or personal data into your logs. Turn `reportInput` on for local debugging, not for production logging. ## Working with issues A worked example: a sign-up schema with a required `email` and a `password` of at least eight characters, parsed against `{ password: "short" }`. ```ts const SignUp = z.object({ email: z.string(), password: z.string().min(8) }); const result = SignUp.safeParse({ password: "short" }); // result.error.issues: // [{ expected: "string", code: "invalid_type", path: ["email"], // message: "Invalid input: expected string, received undefined" }, // { origin: "string", code: "too_small", minimum: 8, inclusive: true, // path: ["password"], message: "Too small: expected string to have >=8 characters" }] ``` A sensible order of use: 1. Check `result.success`; on failure, read `result.error.issues`. 2. Use `path` to attach each issue to a field, and `[]` paths to the form as a whole. 3. Use `code` and its parameters for logic and for translation keys. 4. Show `message` to people, or hand the issues to Zod's formatting helpers, which turn the array into a field-keyed object or a printable string. The issue list is the single source every consumer derives from: a form's field messages, a log line, a translated string. Understanding its fields is what makes the formatting helpers predictable.

  • In Zod 4, how can code tell a missing field from a field of the wrong type?
    Both fail as `invalid_type`, because a missing key reaches the field schema as `undefined`. Inside an error map, the raw issue still carries the input, so `iss.input === undefined` separates the two cases. The finalised issue drops `input` unless the parse ran with `reportInput: true`, so do the distinction inside the error map rather than afterwards.
  • What does a Zod 4 issue look like when a union matches none of its options?
    Zod reports one `invalid_union` issue at the union's path. Its `errors` property holds an array of issue lists, one per option it tried, and its default message is just "Invalid input". A discriminated union with an unknown tag instead reports the allowed tag values in its message, with an empty `errors` array.
  • Is it safe to log Zod 4 issues as they are?
    Mostly, by default: `input` is dropped from each issue, so submitted values are not echoed. Messages can still interpolate rule parameters, such as a regex pattern or the allowed enum values. Turning on `reportInput` puts the raw values back into every issue, so keep it out of production logging.

  • A ZodError reports only the first failure it meets.
  • A missing required field gets its own required issue code.
  • The issue path is a dotted string such as address.zip.
  • Every issue includes the raw input value by default.
  • Program logic should match on the message text.
  • error.errors still lists the issues, as it did in Zod 3.

Assumes Zod 4; Zod 4 merged Zod 3's invalid_enum_value and invalid_literal codes into invalid_value and folded invalid_date into invalid_type.

open as a page

In Zod 4, what happens when schema.parse() and schema.safeParse() receive invalid input, and how do you read each result?

level: juniorimportance: must knowfreq 80%

basics

~20 s

Zod's parse() returns the typed value or throws a ZodError when input fails the schema. safeParse() does not throw on invalid input; it returns { success: true, data } or { success: false, error } holding a ZodError.

open as a page

In Zod 4, what do z.string(), z.number() and z.literal() accept, and why does z.number() reject the string "42"?

level: juniorimportance: must knowfreq 62%

basics

~10 s

Zod 4's scalar schemas check the runtime type without converting: z.string() takes strings, z.number() finite numbers, z.literal() its exact values. "42" is a string, so z.number() rejects it; conversion is opt-in through z.coerce.

open as a page

In Zod 4, what is the difference between adding .refine() and adding .transform() to a schema?

level: juniorimportance: must knowfreq 60%

basics

~20 s

In Zod 4, .refine() adds a custom check: its function returns truthy or falsy, the value passes through unchanged, and a falsy result records an issue with code custom. .transform() replaces the validated value with whatever its function returns.

open as a page

In Zod 4, how do you get a TypeScript type from a schema with z.infer, and why does the call need typeof?

level: juniorimportance: must knowfreq 78%

basics

~20 s

Declare the schema as a value, then write type User = z.infer<typeof User>. The typeof is needed because the schema is a runtime object, and z.infer reads the parsed-output type that Zod attaches to it.

open as a page

In Zod 4, how do you derive create, update and public response schemas from one user schema using pick, omit, partial and extend?

level: middleimportance: must knowfreq 65%

basics

~20 s

Keep one base z.object and derive views from it: omit server-owned fields for create, pick the editable fields then call .partial() for update, omit secrets for the response. Use .extend() rather than the deprecated .merge(), and watch defaults and object-level refinements.

open as a page

In Zod 4, what does z.object do with keys the schema does not declare, and when would you use z.strictObject or z.looseObject instead?

level: middleimportance: must knowfreq 70%

basics

~20 s

Zod 4's z.object strips undeclared keys from the parsed result without raising an issue. z.strictObject fails the parse with an unrecognized_keys issue, and z.looseObject copies unknown keys through unvalidated. Each mode applies only to the object schema it is set on.

open as a page

In Zod 4, how do z.flattenError and z.treeifyError turn a ZodError into field messages for a sign-up form, and when does each fit?

level: middleimportance: must knowfreq 58%

basics

~20 s

z.flattenError returns formErrors for root-level issues and fieldErrors keyed by each issue's first path segment, which suits a flat form. z.treeifyError returns a nested errors/properties/items tree mirroring the schema, which suits nested objects and arrays.

open as a page

In Zod 4, what does z.coerce.number() do to query-string values such as "42", "" and "abc", and what does it accept silently?

level: middleimportance: must knowfreq 58%

basics

~20 s

z.coerce.number() runs Number(input), then the usual finite-number check. "42" becomes 42 and "abc" fails as NaN, but "" becomes 0 and passes, as do " 7 ", "1e3" and "0x1F", so bounds like .int().min(1) must do the rejecting.

open as a page

In Zod 4, how do you check that a sign-up form's password and confirmation match, and which field gets the error?

level: middleimportance: must knowfreq 65%

basics

~20 s

In Zod 4, attach .refine() to the object schema, the only place both fields are visible, and pass path: ["confirmPassword"] so the issue lands on that field. Without path, the issue sits at the object's own path, which is empty at the root.

open as a page

In Zod 4, when do you use z.array, z.tuple or z.record, and how does each treat extra or missing entries?

level: juniorimportance: should knowfreq 45%

basics

~20 s

Use z.array for a list of one type at any length, z.tuple for fixed positions with their own schemas, z.record(keySchema, valueSchema) for dynamic keys. A tuple without a rest schema rejects extra items; an enum-keyed record requires every key.

open as a page

In Zod 4, how does the error param set custom messages, and which Zod 3 options (message, errorMap, required_error, invalid_type_error) did it replace?

level: middleimportance: should knowfreq 48%

basics

~20 s

Zod 4 takes one error param on schemas and checks: a string, or a function of the issue returning a message or undefined to defer. It replaces errorMap, deprecates message, and drops required_error and invalid_type_error.

open as a page

In Zod 4, after safeParse succeeds on a webhook body, why pass result.data inward instead of the original body object?

level: middleimportance: should knowfreq 50%

basics

~20 s

Zod's result.data is a new value built from the schema: z.object() drops unknown keys by default, defaults are filled and transforms applied. The original body still holds whatever the sender sent, so only result.data matches the inferred type.

open as a page

In Zod 4, how does z.enum() validate a TypeScript enum compared with a string array, and what replaced z.nativeEnum()?

level: middleimportance: should knowfreq 40%

basics

~20 s

In Zod 4, z.enum() accepts both a string array and an enum-like object, so z.nativeEnum() is deprecated. Either way it checks values, not member names: enum Priority { Low = 1, High = 2 } accepts 1 and 2 but rejects "Low" and the text "1".

open as a page

Why does Zod 4 offer z.email(), z.uuid() and z.iso.datetime() as top-level schemas instead of z.string().email(), and what changed in what they accept?

level: middleimportance: should knowfreq 44%

basics

~20 s

In Zod 4 string formats are ZodString subclasses exposed at the top level, shorter and tree-shakable; z.string().email() still works but is deprecated. z.uuid() now enforces RFC variant bits (z.guid() is looser), and z.iso.datetime() rejects offsets unless configured.

open as a page

In Zod 4, what is the difference between .default(), .prefault() and .catch() on a schema?

level: middleimportance: should knowfreq 35%

basics

~20 s

In Zod 4, .default() returns its value as-is when the input is undefined, skipping validation. .prefault() substitutes its value for undefined and then parses it. .catch() returns its fallback whenever validation fails, whatever the input was.

open as a page

In Zod 4, how do you type a category tree schema whose subcategories nest the same schema, and what fixes a circularity error?

level: middleimportance: should knowfreq 32%

basics

~20 s

Put the self-reference in a getter on the shape: get subcategories() { return z.array(Category) }. z.infer then yields a recursive type with no hand-written interface. If TypeScript reports an implicit-any circularity error, annotate that getter's return type.

open as a page

Your service receives event payloads that differ by a type field. In Zod 4, why choose z.discriminatedUnion over z.union, and how do the errors differ?

level: seniorimportance: should knowfreq 50%

basics

~20 s

z.discriminatedUnion reads the type field and runs only the matching option, so errors land on that option's fields or on the type path. z.union tries options in order, keeps the first success and usually fails with one vague invalid_union issue.

open as a page

In Zod 4, z.string("Username is required").min(3) reports "Username is required" for "ab", and the error map passed to safeParse is ignored. Why?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Zod 4 picks the most specific message: check-level, then schema-level, then the per-parse map, then the global customError, then the locale. A schema-level string covers its own checks that lack a message, and outranks the per-parse map.

open as a page

A Zod 4 webhook schema gains an async refinement that looks up the event ID, and safeParse now throws 'Encountered Promise during synchronous parse'. Why, and what fixes it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Zod's synchronous parse and safeParse cannot await, so when a refinement returns a Promise they throw a plain Error instead of reporting an issue. Parse that schema, and every schema embedding it, with safeParseAsync or parseAsync.

open as a page

Why does a Zod 4 search schema that declares active as z.coerce.boolean() turn the query value active=false into true, and what should replace it?

level: seniorimportance: should knowfreq 48%

basics

~20 s

z.coerce.boolean() calls Boolean(input), and every non-empty string, "false" included, is truthy, so it becomes true. Replace it with z.stringbool(), added in Zod 4.0, which maps listed words such as "false", "0" and "no" to false and rejects unlisted text.

open as a page

In Zod 4, you add an async .refine() that checks whether a sign-up username is already taken, and every caller already uses safeParseAsync. What can still go wrong?

level: seniorimportance: should knowfreq 40%

basics

~20 s

In Zod 4, the lookup still runs after continuable failures such as a too-short name, unless that check sets abort true or the refinement uses when. A rejected lookup escapes as an exception, not an issue, and the check is only a pre-check; the store's uniqueness rule is the real guarantee.

open as a page

In Zod 4, when normalising an email and a price string on input, how do .transform(), z.preprocess() and .pipe() differ in when they run?

level: seniorimportance: should knowfreq 45%

basics

~20 s

In Zod 4, z.preprocess() runs a function on the raw, unknown input before its target schema validates it. .transform() runs only after its schema has accepted the value. .pipe() feeds one schema's output into a second schema, which validates the converted value.

open as a page

In Zod 4, what does .brand<"UserId">() change about a schema's inferred type and parse result, and how does that keep UserId and OrderId apart?

level: seniorimportance: should knowfreq 38%

basics

~20 s

It intersects the schema's output type with z.$brand<"UserId">, so short of a cast, only values returned by that schema's parse fit a UserId parameter, and an OrderId does not. The runtime value stays a plain string, and by default the input type is unbranded.

open as a page

In Zod 4, a user schema turns createdAt from an ISO string into a Date and defaults role when absent; what do z.input and z.output give, and which does each signature need?

level: seniorimportance: should knowfreq 52%

basics

~20 s

z.input is what parse accepts: createdAt a string, role an optional key. z.output, which z.infer aliases, is what parse returns: createdAt a Date, role required. Raw data before parsing takes the input type; code after parsing takes the output type.

open as a page

As the lead of a TypeScript service on Zod 4, would you standardise request and response schemas on strip, strict or loose unknown-key handling, and why?

level: principalimportance: should knowfreq 30%

basics

~20 s

No single mode fits. A common policy: z.strictObject for write bodies from clients you redeploy, plain z.object for third-party responses and outbound views, z.looseObject only for forwarded data. Zod has no global switch, so enforce it by convention.

open as a page

As the lead standardising Zod 4 in a TypeScript service, which parse call would you mandate at each boundary, and what does parse-once-then-trust commit the team to?

level: principalimportance: should knowfreq 30%

basics

~20 s

With Zod, pick the call by who owns a failure: parse for startup config so a bad deploy crashes, safeParse for requests, third-party responses and stored JSON. Pass only parsed values inward, typed with z.infer, and treat schemas as contracts.

open as a page

In Zod 4, how should a command-line tool print a config-file validation failure, and why not print the ZodError's message property?

level: middleimportance: nice to knowfreq 24%

basics

~20 s

Pass the error to z.prettifyError, which returns one line per issue plus an arrow line with a dotted path, root-level issues first. A ZodError's message property is a pretty-printed JSON dump of the issues array, written for machines.

open as a page

In Zod 4, why is calling z.config(z.locales.fr()) inside a request handler a fragile way to localise validation messages per user, and what would you do instead?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

z.config writes one process-wide config, so a per-request locale leaks into other requests and can race with async parses. Instead pass a per-parse error map for the user's language, or translate issue codes at render time.

open as a page

In Zod 4, what does a z.codec() give you over .transform() when a booking timestamp crosses the network as an ISO string?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

Since Zod 4.1, z.codec(in, out, { decode, encode }) defines a two-way conversion: parse or decode turns the ISO string into a Date, and encode turns the Date back into a validated string. A .transform() only runs forward, and encoding through one throws.

open as a page

showing 1–30 of 31