Skip to content

Latest commit

 

History

History
79 lines (63 loc) · 2.3 KB

File metadata and controls

79 lines (63 loc) · 2.3 KB
title Checking Option and Either Cases
id pattern-option-either-checks
skillLevel beginner
applicationPatternId error-management
summary Use isSome, isNone, isLeft, and isRight to check Option and Either cases for simple, type-safe branching.
tags
isSome
isNone
isLeft
isRight
pattern-matching
option
either
checks
rule
description
Use isSome, isNone, isLeft, and isRight to check Option and Either cases for simple, type-safe conditional logic.
related
pattern-option-either-match
pattern-match
author PaulJPhilp
lessonOrder 1

Checking Option and Either Cases

Guideline

Use the isSome, isNone, isLeft, and isRight predicates to check the case of an Option or Either for simple, type-safe branching.
These are useful when you need to perform quick checks or filter collections based on presence or success.

Rationale

These predicates provide a concise, type-safe way to check which case you have, without resorting to manual property checks or unsafe type assertions.

Good Example

import { Option, Either } from "effect";

// Option: Check if value is Some or None
const option = Option.some(42);

if (Option.isSome(option)) {
  // option.value is available here
  console.log("We have a value:", option.value);
} else if (Option.isNone(option)) {
  console.log("No value present");
}

// Either: Check if value is Right or Left
const either = Either.left("error");

if (Either.isRight(either)) {
  // either.right is available here
  console.log("Success:", either.right);
} else if (Either.isLeft(either)) {
  // either.left is available here
  console.log("Failure:", either.left);
}

// Filtering a collection of Options
const options = [Option.some(1), Option.none(), Option.some(3)];
const presentValues = options.filter(Option.isSome).map((o) => o.value); // [1, 3]

Explanation:

  • Option.isSome and Option.isNone let you check for presence or absence.
  • Either.isRight and Either.isLeft let you check for success or failure.
  • These are especially useful for filtering or quick conditional logic.

Anti-Pattern

Manually checking internal tags or properties (e.g., option._tag === "Some"), or using unsafe type assertions, which is less safe and less readable than using the provided predicates.