Schema module provides powerful runtime validation and type-safe schema definitions for TypeScript applications. It enables you to define data structures once and use them for validation, parsing, serialization, and type inference.
Overview
A Schema defines both:- The encoded representation (e.g., what comes from an API or user input)
- The type representation (e.g., your application’s domain model)
- Runtime validation and parsing
- Type inference for TypeScript
- JSON Schema generation
- Serialization and deserialization
- Custom error messages
Creating Schemas
Primitive Types
Structs and Objects
Optional and Nullable Fields
Arrays and Collections
Parsing and Validation
Using makeUnsafe
Using makeOption
With Effect Integration
Custom Validations
Refinements
Transformations
Tagged Errors
Union Types
Records and Dictionaries
Annotations and Documentation
Type Inference
Best Practices
- Define schemas at the boundaries: Validate external data at API boundaries
- Use Schema.TaggedErrorClass: Define custom errors with schemas for better type safety
- Compose schemas: Build complex schemas from simpler ones
- Add annotations: Document your schemas for better JSON Schema generation and error messages
- Prefer makeOption over makeUnsafe: Use
makeOptionwhen validation failure is expected