Advance typing with Zod
Learn how to use Zod schemas to define strongly-typed components in Hydra AI
Using Zod with Hydra AI Components
Hydra AI recommends using Zod for component prop validation. Zod provides runtime type checking and automatic TypeScript type inference, making your components more reliable and easier to maintain.
Getting Started
First, install the required dependencies:
Component Registration with Zod
Here's how to register components using Zod schemas:
Organizing Component Registration
For larger applications, it's recommended to organize your schemas and registrations:
Adding Context Tools
Components can include context tools for data fetching:
Best Practices
-
Separate Schema Definitions: Keep your Zod schemas in a separate file (e.g.,
model/hydra-carousel.ts
) for better organization. -
Use Type Inference:
- Centralize Registration: Create a single function to handle all component registrations:
Type Safety with Context Tools
When using context tools, ensure your schema matches the returned data:
This approach provides a robust way to register components with type safety while maintaining clean and maintainable code. The zodToJsonSchema
conversion allows Hydra to understand your Zod schemas while preserving all type information for runtime validation.