What are decoders?
TypeScript provides compile-time type safety, but it can’t validate data that arrives at runtime from external sources like APIs, user input, or configuration files. Decoders bridge this gap by:- Validating data structure and types at runtime
- Inferring TypeScript types automatically from your validation rules
- Providing clear error messages when validation fails
- Transforming data while maintaining type safety
Why use decoders?
TypeScript can’t validate runtime data
TypeScript’s type system only exists at compile time. When data comes from external sources, TypeScript has no way to verify it matches your types:Decoders provide runtime safety
With decoders, you validate and type-check data at runtime:Key features
Automatic type inference
TypeScript automatically infers types from your decoder definitions - no need to write types twice
Composable
Build complex validators from simple, reusable building blocks
Zero dependencies
Tiny bundle size (~4KB) with zero runtime dependencies and full tree-shaking support
Excellent errors
Detailed error messages that pinpoint exactly what went wrong and where
Battle-tested
Used in production by thousands of projects with comprehensive test coverage
Cross-platform
Works in Node.js, browsers, Bun, Deno, and Cloudflare Workers
Basic example
Here’s a complete example showing how decoders work:.verify() throws an error with a detailed message.
When to use decoders
Use decoders whenever you need to validate untrusted data:- API responses - Validate data from external APIs
- User input - Validate form submissions and user-provided data
- Configuration files - Validate JSON/YAML configuration
- Database queries - Validate data from databases
- Message queues - Validate messages from queues like RabbitMQ or Kafka
- Environment variables - Validate and parse environment configuration
- File uploads - Validate uploaded file contents
How it works
Decoders use a simple three-step process:Define a decoder
Create a decoder that describes the expected data structure using composable decoder functions.
Comparison with other libraries
| Feature | Decoders | Zod | Yup | io-ts |
|---|---|---|---|---|
| Bundle size | ~4KB | ~12KB | ~16KB | ~8KB |
| Dependencies | 0 | 0 | Several | fp-ts |
| Type inference | ✓ | ✓ | Limited | ✓ |
| Composable | ✓ | ✓ | ✓ | ✓ |
| Error messages | Excellent | Good | Good | Complex |
| Learning curve | Low | Medium | Low | High |
Next steps
Installation
Install decoders and set up your project
Quickstart
Build your first decoder in 5 minutes
Core concepts
Understand how decoders work under the hood
API reference
Explore the complete API documentation
