decodeSync

Avatar of Hemanta SundarayHemanta Sundaray

decodeSync is a synchronous decoder.

On decode failure, it throws a native JavaScript Error. The human-readable message is on error.message, and the structured issue tree is on error.cause.

decodeSync is the typed-input variant of decodeUnknownSync, meaning it accepts the schema’s Encoded type as input instead of unknown, so TypeScript enforces the correct input shape at compile time.

The Encoded type is the shape of the data before decoding. For example, consider a simple schema like Schema.String. A string goes in, a string comes out. Both the Encoded type and the Type (the decoded type) are strings. Now consider Schema.NumberFromString. This is a transformation schema. A string goes in (like "42"), and a number comes out (like 42). The Encoded type is string and the Type is number.

schema.ts
import { Schema, SchemaIssue } from "effect";
const schema = Schema.Struct({
name: Schema.String,
age: Schema.NumberFromString, // Encoded: string, Decoded: number
});
const decode = Schema.decodeSync(schema);
// Happy path
const decoded = decode({ name: "Alice", age: "30" });
console.log("Decoded Value:", decoded);
// Error path
try {
// age should be string in encoded input
decode({ name: "Alice", age: 30 } as any);
} catch (error) {
if (error instanceof Error) {
console.log("Error Message:", error.message);
if (SchemaIssue.isIssue(error.cause)) {
console.log("Issue Tree:", error.cause);
}
}
}

In the example above, age uses Schema.NumberFromString, so its Encoded input type is string. I intentionally passed a number (30) and used as any to bypass TypeScript so I could demonstrate the runtime error path.

Use decodeSync when you have data that you know matches the encoded shape. For example, you store data in localStorage as { price: "19.99", quantity: "3" }. When you read it back, you know the shape is all strings. You use decodeSync to transform them into numbers.

Difference between decodeUnknownSync and decodeSync

decodeUnknownSync accepts unknown input, while decodeSync accepts the schema’s Encoded input type, so TypeScript can catch shape mismatches before runtime.

Sign in to save progress

Stay in the loop

Get notified when new chapters are added and when this course is complete.