Effect.ts: Absence as First-Class

Data TypesLesson 28 of 51

28. Either - Absence WITH Context

Like Option, but the absence tells you WHY it's absent

Code Example
import { Either } from "effect";

// Option: value present or absent
// Either: value present OR specific failure

const parseAge = (input: string): Either<number, string> => {
  const num = parseInt(input);
  if (isNaN(num)) {
    return Either.left("Not a number!");  // WHY absent
  }
  if (num < 0) {
    return Either.left("Age can't be negative!");  // WHY absent
  }
  return Either.right(num);  // Present!
};

// Either<number, string>
//        ^^^^^^  ^^^^^^
//        Success type
//                Failure context

parseAge("25");    // Right(25)
parseAge("abc");   // Left("Not a number!")
parseAge("-5");    // Left("Age can't be negative!")
Interactive Example
const { Either } = await import('effect');
const parseAge = (input) => {
      const num = parseInt(input);
      if (isNaN(num)) return Either.left('Not a number!');
      if (num < 0) return Either.left('Negative age!');
      return Either.right(num);
};
const r1 = parseAge('25');
const r2 = parseAge('abc');
const r3 = parseAge('-5');
const m1 = Either.match(r1, { onLeft: e => 'Error: ' + e, onRight: n => 'Success: ' + n });
const m2 = Either.match(r2, { onLeft: e => 'Error: ' + e, onRight: n => 'Success: ' + n });
const m3 = Either.match(r3, { onLeft: e => 'Error: ' + e, onRight: n => 'Success: ' + n });
return `Either type!

'25': ${m1}
'abc': ${m2}
'-5': ${m3}

✓ Errors have context!`;
Explanation

Either: typed absence with failure context.

Option says: "value might be absent" Either says: "value is absent, and here's WHY"

Traditional approach: throw errors or return null Either types contextual absence:

  • Right(value): value is present
  • Left(error): value is absent, with explanation
  • No assumptions about success
  • Failure type carries information

Absence-first error handling: absence has a story to tell!


Part 28 of 51 in the Effect.ts Absence Modeling series