| 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 |
|
||||||||
| rule |
|
||||||||
| related |
|
||||||||
| author | PaulJPhilp | ||||||||
| lessonOrder | 1 |
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.
These predicates provide a concise, type-safe way to check which case you have, without resorting to manual property checks or unsafe type assertions.
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.isSomeandOption.isNonelet you check for presence or absence.Either.isRightandEither.isLeftlet you check for success or failure.- These are especially useful for filtering or quick conditional logic.
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.