Type Safety
MoroJS provides end-to-end type safety throughout your entire API, from request validation to response serialization. Learn how TypeScript integration makes your APIs more reliable and maintainable.
Why Type Safety Matters
Type safety in APIs prevents entire categories of runtime errors and provides excellent developer experience:
- Catch errors at compile time, not in production
- IntelliSense and autocompletion for all API data
- Automatic validation of request/response schemas
- Self-documenting code that's easier to maintain
Request Type Safety
MoroJS automatically infers types from your route patterns and validation schemas:
Automatic Parameter Type Inference
typescript
Query Parameter Types
typescript
Schema-Based Validation with Zod
Define schemas once and get both runtime validation and compile-time types:
Request Body Validation
typescript
Parameter Validation
typescript
Response Type Safety
Define response schemas to ensure your API returns consistent data:
Response Schema Definition
typescript
Context Type Safety
Middleware can add typed data to the request context:
Typed Middleware Context
typescript
Best Practices
Do
- • Define schemas for all inputs and outputs
- • Use strict TypeScript configuration
- • Leverage z.infer for type extraction
- • Create reusable schema components
- • Use branded types for IDs
- • Document complex types with JSDoc
Don't
- • Use 'any' types
- • Skip validation for external data
- • Ignore TypeScript errors
- • Mix validated and unvalidated data
- • Use type assertions without validation
- • Forget to handle all response cases
Advanced Type Patterns
Branded Types for Better Safety
typescript
Conditional Response Types
typescript