Schema Definition
A schema defines the shape and validation rules for your data. Start by defining a simple object schema:Parsing Data
1
Use .parse() for validation
The
.parse() method validates input and returns a deep clone if valid. It throws a ZodError if validation fails:2
Handle validation errors
When parsing fails, Zod throws a detailed error:
3
Use .safeParse() to avoid exceptions
For error handling without try/catch, use
.safeParse(). It returns a discriminated union:Type Inference
Zod automatically infers TypeScript types from your schemas usingz.infer<> or z.output<>:
For schemas with transformations, use
z.input<> to get the input type and z.output<> (or z.infer<>) to get the output type.Input vs Output Types
When you use transforms, input and output types can differ:Error Handling
Zod provides detailed error information when validation fails.Working with ZodError
Every failed parse produces aZodError with an issues array:
Custom Error Messages
You can provide custom error messages when defining schemas:Complete Example
Here’s a complete example combining all concepts:Next Steps
Primitives
Explore all primitive types: strings, numbers, dates, and more
Objects
Learn about object schemas, nesting, and composition
Arrays & Tuples
Work with arrays, tuples, and collections
Advanced Types
Master unions, intersections, and discriminated unions