| id |
schema-decode-encode |
| title |
Decode and Encode Data |
| category |
getting-started |
| skillLevel |
beginner |
| tags |
schema |
decode |
encode |
parsing |
serialization |
|
| lessonOrder |
16 |
| rule |
| description |
Decode and Encode Data using Schema. |
|
| summary |
You receive data as JSON and need to convert it to typed objects. Later, you need to serialize those objects back to JSON for storage or API responses. Without a consistent approach, you write... |
You receive data as JSON and need to convert it to typed objects. Later, you need to serialize those objects back to JSON for storage or API responses. Without a consistent approach, you write parsing code in one place and serialization code elsewhere—they drift apart and bugs creep in.
import { Schema } from "effect"
// Define schema once—use for both decode and encode
const Product = Schema.Struct({
id: Schema.String,
name: Schema.String,
price: Schema.Number,
inStock: Schema.Boolean,
})
type Product = typeof Product.Type
// Create decoder and encoder from same schema
const decode = Schema.decodeUnknownSync(Product)
const encode = Schema.encodeSync(Product)
// DECODE: unknown → typed Product
const rawJson = {
id: "prod_123",
name: "Widget",
price: 29.99,
inStock: true
}
const product: Product = decode(rawJson)
console.log(`Decoded: ${product.name} - $${product.price}`)
// Output: Decoded: Widget - $29.99
// Use the typed product in your code
if (product.inStock) {
console.log("✅ Available for purchase")
}
// ENCODE: typed Product → unknown (for JSON serialization)
const jsonOutput = encode(product)
console.log(`Encoded: ${JSON.stringify(jsonOutput)}`)
// Output: Encoded: {"id":"prod_123","name":"Widget","price":29.99,"inStock":true}
| Concept |
Explanation |
| Single source of truth |
One schema defines both parsing and serialization |
| decodeUnknownSync |
Parses and validates unknown data to typed value |
| encodeSync |
Converts typed value back to serializable format |
| Type safety |
TypeScript knows the exact type after decode |
| Bidirectional |
Same schema handles input and output |
- Receiving JSON from APIs and returning JSON responses
- Reading config files and writing them back
- Caching objects (serialize) and restoring them (deserialize)
- Any round-trip data transformation