Effect.ts: Absence as First-Class

Data TypesLesson 26 of 51

26. Option - Modeling "Maybe Absent"

Option types values that might not exist - no nulls, no undefined!

Code Example
// Traditional: null/undefined everywhere
function findUser(id: string): User | null {
  const user = db.find(id);
  return user ?? null;  // Might be absent
}

// Effect Option: type the absence!
import { Option } from "effect";

const findUser = (id: string): Option<User> =>
  Option.fromNullable(db.find(id));

// Type tells the story:
// Option<User>
//        ^^^^
//        User might be absent!

// Handle absence explicitly:
const greeting = findUser("123").pipe(
  Option.match({
    onNone: () => "Guest",
    onSome: (user) => `Hello ${user.name}!`
  })
);
Interactive Example
const { Option } = await import('effect');
const found = Option.some(42);
const missing = Option.none();
const result1 = Option.match(found, {
      onNone: () => 'Not found',
      onSome: (n) => 'Found: ' + n
});
const result2 = Option.match(missing, {
      onNone: () => 'Not found',
      onSome: (n) => 'Found: ' + n
});
return `Option type!

Some(42): ${result1}
None: ${result2}

No null/undefined!`;
Explanation

Option: typing "maybe absence" without null/undefined.

Traditional approach: null/undefined spread through code like a virus. Option types presence-uncertainty as first-class:

  • Some(user): "This value exists"
  • None: "This value is absent"
  • No assumptions about existence
  • Type system forces handling both cases

This is absence-first safety: can't forget to handle missing values!


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