Overview
Codecs provide bidirectional transformation between two representations of data. They combine input validation, output validation, and reversible transformations.Basic Codec
Create a codec usingz.codec() with two schemas and transformation functions:
Codec Structure
A codec is defined with:- Input Schema (A): Validates the encoded form
- Output Schema (B): Validates the decoded form
- decode: Transforms
A→B(forward direction) - encode: Transforms
B→A(backward direction)
Codec Operations
Decode (Forward)
Transform from input to output representation:Encode (Backward)
Transform from output back to input representation:Async Operations
All codec operations support async transformations:Round-Trip Conversion
Codecs guarantee bidirectional transformation:Codec Type Signatures
The type system ensures correct transformations:Codecs with Refinements
Add refinements to codec schemas:Complex Codec Example
Nested object with codec property:Validation at Multiple Levels
Codecs validate at each level:Mutating Refinements
Codecs support refinements that mutate data:Codec with Overwrites
Apply transformations after codec operations:Instance Checks
Error Handling
Best Practices
- Ensure reversibility - Encoding after decoding should return the original value
- Validate both directions - Both input and output schemas should have proper validation
- Use refinements for constraints - Add refinements to enforce additional rules
- Handle edge cases - Consider how transformations handle null, undefined, edge values
- Type safety - Let TypeScript infer types from codec definitions
- Async when needed - Use async transforms for I/O operations
Codecs are perfect for API serialization, database value conversion, and any scenario requiring reversible transformations with validation.