Zod provides TypeScript-first schema validation. Here's how to use it for forms, APIs, and data transformation.
Basic Schemas#
Object Schemas#
Array and Tuple Schemas#
Union and Discriminated Union#
Transformations#
Custom Validation with Refine#
React Hook Form Integration#
API Validation#
Best Practices#
Schemas:
✓ Define schemas close to usage
✓ Reuse common schemas
✓ Use discriminated unions for tagged types
✓ Export inferred types
Validation:
✓ Provide helpful error messages
✓ Use coercion for external input
✓ Validate at system boundaries
✓ Handle async validation carefully
Performance:
✓ Parse once, use types after
✓ Avoid excessive refinements
✓ Cache compiled schemas
✓ Use strict mode appropriately
Conclusion#
Zod bridges runtime validation and TypeScript types. Use object schemas for structured data, discriminated unions for tagged types, and transformations for data cleaning. Integration with React Hook Form and tRPC makes Zod essential for full-stack TypeScript applications.