EffectTalk
Back to Tour
domain-modelingIntermediate

Parse and Validate Data with Schema.decode

Use Schema.decode(schema) to create an Effect that parses and validates unknown data, which integrates seamlessly with Effect's error handling.

Parse and Validate Data with Schema.decode

Guideline

When you need to parse or validate data against a Schema, use the Schema.decode(schema) function. It takes an unknown input and returns an Effect.

Rationale

Unlike the older Schema.parse which throws, Schema.decode is fully integrated into the Effect ecosystem, allowing you to handle validation failures gracefully with operators like Effect.catchTag.

Good Example

import { Effect, Schema } from "effect";

interface User {
  name: string;
}

const UserSchema = Schema.Struct({
  name: Schema.String,
}) as Schema.Schema<User>;

const processUserInput = (input: unknown) =>
  Effect.gen(function* () {
    const user = yield* Schema.decodeUnknown(UserSchema)(input);
    return `Welcome, ${user.name}!`;
  }).pipe(
    Effect.catchTag("ParseError", () => Effect.succeed("Invalid user data."))
  );

// Demonstrate the schema parsing
const program = Effect.gen(function* () {
  // Test with valid input
  const validInput = { name: "Paul" };
  const validResult = yield* processUserInput(validInput);
  yield* Effect.logInfo(`Valid input result: ${validResult}`);

  // Test with invalid input
  const invalidInput = { age: 25 }; // Missing 'name' field
  const invalidResult = yield* processUserInput(invalidInput);
  yield* Effect.logInfo(`Invalid input result: ${invalidResult}`);

  // Test with completely invalid input
  const badInput = "not an object";
  const badResult = yield* processUserInput(badInput);
  yield* Effect.logInfo(`Bad input result: ${badResult}`);
});

Effect.runPromise(program);

Explanation:
Schema.decode integrates parsing and validation into the Effect workflow, making error handling composable and type-safe.

Anti-Pattern

Using Schema.parse(schema)(input), as it throws an exception. This forces you to use try/catch blocks, which breaks the composability of Effect.

Parse and Validate Data with Schema.decode | EffectTalk | EffectTalk