Type Safety
Leverage TypeScript and Zod for end-to-end type safety in your APIs
Type Safety
Frey is built with TypeScript and leverages Zod for end-to-end type safety. This ensures that your API is type-safe from schema definition to runtime validation.
Schema-Driven Types
When you define a Zod schema, Frey automatically infers TypeScript types:
Handler Type Safety
Your entity handlers are fully type-safe:
Context Type Safety
The context object passed to handlers is fully typed:
Custom Route Type Safety
Custom routes also benefit from type safety:
Advanced Type Patterns
Conditional Types
Use TypeScript's conditional types for advanced scenarios:
Generic Entity Types
Create reusable entity types:
Union Types
Use union types for flexible schemas:
Runtime Validation
Zod schemas provide runtime validation in addition to compile-time type safety:
Error Handling with Types
Handle errors in a type-safe way:
Type Guards
Use type guards for runtime type checking:
Best Practices
- Use strict TypeScript: Enable strict mode in your TypeScript configuration
- Leverage Zod inference: Let Zod infer types instead of manually defining them
- Validate at boundaries: Validate data at API boundaries (request/response)
- Use type guards: Implement type guards for runtime type checking
- Handle errors gracefully: Always handle potential type errors
- Document complex types: Add JSDoc comments for complex type definitions
TypeScript Configuration
Recommended TypeScript configuration for Frey projects:
Common Type Patterns
API Response Types
Error Types
Next Steps
- Learn about Parameter Handling for advanced querying
- Explore Custom Routes for advanced functionality
- Check out Examples for real-world implementations