Either: Left<E> | Right<A>

A value of Either type Left<E> or type Right<A>; a disjoint union.

A common use case is as an alternative to Option where Left<E> contains useful information. Convention dictates that Left<E> is used for failure and Right<A> for success. To help remember, the success case is "right"; it's the result you want.

Type Parameters

  • E
  • A
import { equal } from "node:assert/strict";

import { either as E, pipe } from "@clipboard-health/util-ts";

function double(n: number): number {
return n * 2;
}

function inverse(n: number): E.Either<string, number> {
return n === 0 ? E.left("Division by zero") : E.right(1 / n);
}

const result = pipe(
E.right(5),
E.map(double),
E.flatMap(inverse),
E.match(
(error) => `Error: ${error}`,
(result) => `Result is ${result}`,
),
);

equal(result, "Result is 0.1");