EffectTalk
Back to Tour
getting-startedBeginner

Transform Values with Effect.map

Use Effect.map to transform the success value of an Effect without changing its error or dependency types.

Transform Values with Effect.map

Guideline

Use Effect.map to transform the success value inside an Effect. The transformation function receives the value and returns a new value.

Rationale

Just like Array.map transforms array elements, Effect.map transforms the success value of an Effect. This lets you build pipelines of transformations without running anything until the end.

Good Example

import { Effect } from "effect";

// Start with an Effect that succeeds with a number
const getNumber = Effect.succeed(5);

// Transform it: multiply by 2
const doubled = Effect.map(getNumber, (n) => n * 2);

// Transform again: convert to string
const asString = Effect.map(doubled, (n) => `The result is ${n}`);

// Run to see the result
const result = Effect.runSync(asString);
console.log(result); // "The result is 10"

Using pipe for Cleaner Code

import { Effect, pipe } from "effect";

const result = pipe(
  Effect.succeed(5),
  Effect.map((n) => n * 2),
  Effect.map((n) => n + 1),
  Effect.map((n) => `Final value: ${n}`),
  Effect.runSync
);

console.log(result); // "Final value: 11"

Real-World Example

import { Effect, pipe } from "effect";

interface User {
  id: number;
  name: string;
  email: string;
}

const fetchUser = Effect.succeed<User>({
  id: 1,
  name: "Alice",
  email: "alice@example.com",
});

// Extract just the name from the user
const getUserName = pipe(
  fetchUser,
  Effect.map((user) => user.name)
);

// Format the name for display
const getDisplayName = pipe(
  fetchUser,
  Effect.map((user) => user.name.toUpperCase())
);

Effect.runSync(Effect.all([getUserName, getDisplayName]));
// ["Alice", "ALICE"]

Key Points

  1. Effect.map only transforms success values - errors pass through unchanged
  2. The original Effect is unchanged - map creates a new Effect
  3. Nothing runs until you call runSync/runPromise - you're just building a pipeline

What's Next?

  • Learn Effect.flatMap for chaining Effects that return other Effects
  • Learn error handling with Effect.catchAll