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

  1. Use strict TypeScript: Enable strict mode in your TypeScript configuration
  2. Leverage Zod inference: Let Zod infer types instead of manually defining them
  3. Validate at boundaries: Validate data at API boundaries (request/response)
  4. Use type guards: Implement type guards for runtime type checking
  5. Handle errors gracefully: Always handle potential type errors
  6. 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