A useful program rarely does one thing.
It parses an id. Then it fetches a user. Then it checks a permission. Then it writes something.
That is where flatMap shows up.
flatMap means:
If this Effect succeeds, use its value to choose the next Effect.
The plain version
Here is that chain with promises:
const getUser = async (input: string): Promise<User> => { const id = parseUserId(input); const user = await fetchUser(id);
return user;};It reads well.
Each line waits for the one above it.
The type says Promise<User>.
It does not say the id can be invalid. It does not say the user can be missing.
Both failures leave through throw. The caller finds out at runtime.
The caller also cannot tell which step failed without reading both functions.
With Effect, the chain looks almost the same. The difference is in the type.
A small chain
const parseUserId = (input: string) => Number.isInteger(Number(input)) ? Effect.succeed(Number(input)) : Effect.fail(new InvalidUserId(input));
const fetchUser = (id: number) => id === 1 ? Effect.succeed({ id, name: "Ada" }) : Effect.fail(new UserNotFound(id));
const program = parseUserId("1").pipe(Effect.flatMap((id) => fetchUser(id)));The second step needs the value from the first step.
That is why this is flatMap.
Failure skips the rest
If parseUserId("abc") fails, fetchUser does not run.
That is the part I like.
The happy path reads straight down. The failure path stays in the type.
Effect.Effect<User, InvalidUserId | UserNotFound, never>;The program can fail in either step.
The mistake: a callback that returns nothing
Braces change what an arrow function returns.
A one-line arrow returns its expression. A block body returns nothing unless you write return.
Effect code is full of arrows, so this comes up often.
parseUserId("1").pipe( Effect.flatMap((id) => { fetchUser(id); }),);This builds a fetchUser Effect and drops it.
The callback returns void.
TypeScript catches this one. The error says void is not assignable to Effect.
When you see that message, look for a missing return.
The fix is one word.
Or drop the braces:
parseUserId("1").pipe(Effect.flatMap((id) => fetchUser(id)));The part that finally clicked
This:
parseUserId("1").pipe(Effect.flatMap(fetchUser));is the Effect version of:
const id = parseUserId("1");const user = fetchUser(id);Except the failures are not hiding.
They are part of the result.

