Skip to main content
Version: 0.3

Branching

branch routes a tagged union to different handlers based on its kind discriminant. Each case handler receives the unwrapped payload — not the full { kind, value } wrapper.

Basic branching

From demos/convert-folder-to-ts/handlers/type-check-fix.ts:

export const typeCheckFix = loop((recur) =>
pipe(typeCheck, classifyErrors).branch({
HasErrors: pipe(forEach(fix).drop(), recur),
Clean: drop,
}),
);

classifyErrors returns a tagged union — either { kind: "HasErrors", value: string[] } or { kind: "Clean", value: void }. The HasErrors handler receives the string[] of errors directly; the Clean handler receives void.

Branching with Result types

Result combinators like .unwrapOr() are built on branch internally. You can also branch on Results explicitly:

pipe(
riskyStep,
branch({
Ok: processSuccess,
Err: handleFailure,
}),
)

Branching with Option types

The same pattern works for Option<T>:

pipe(
maybeFind,
branch({
Some: processFound,
None: constant("not found"),
}),
)