Boundary validation
Validate request bodies, configuration, or other external data before application logic consumes it.
Zod · Function
Validates unknown input against a Zod schema. It returns a strongly typed deep clone on success and throws a ZodError on failure.
Call parse on a Zod schema with unknown input. When validation succeeds, it returns a strongly typed deep clone; when validation fails, it throws a ZodError, so use try/catch when handling expected invalid input.
schema.parse(data: unknown): T| Name | Type | Description |
|---|---|---|
data | unknown | The value to validate against the schema; its compile-time type is unknown. |
T on success; throws ZodError when validation fails.
import { z } from "zod";
const Player = z.object({
username: z.string(),
xp: z.number(),
});
const player = Player.parse({ username: "billie", xp: 100 });
console.log(player.username);Validates the input and returns the parsed, strongly typed player value.
Validate request bodies, configuration, or other external data before application logic consumes it.
Convert untrusted input into a schema-shaped value with inferred TypeScript types.
Fail immediately when required data does not satisfy a schema.
parse validates unknown input against a schema. On success it returns a strongly typed deep clone; on failure it throws a ZodError.
Follow-up: How would you avoid exceptions for ordinary validation failures? Use safeParse, which returns an object containing either parsed data or a ZodError.
The returned value is a deep clone of the input, so callers receive validated data without retaining the original object's identity.
Follow-up: Why might this matter for mutable objects? Mutating the parsed result does not mutate the original input object through shared nested references.
parse is synchronous and cannot complete asynchronous refinements or transforms. In those cases, parseAsync must be awaited.
Follow-up: What alternative handles asynchronous validation without throwing? safeParseAsync returns a result object for asynchronous success or failure.
safeParseparseAsyncsafeParseAsyncZodError