| title | Converting from Nullable, Option, or Either | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| id | constructor-from-nullable-option-either | ||||||||||
| skillLevel | beginner | ||||||||||
| applicationPatternId | core-concepts | ||||||||||
| summary | Use fromNullable, fromOption, and fromEither to convert nullable values, Option, or Either into Effects or Streams, enabling safe and composable interop. | ||||||||||
| tags |
|
||||||||||
| rule |
|
||||||||||
| related |
|
||||||||||
| author | PaulJPhilp | ||||||||||
| lessonOrder | 7 |
Use the fromNullable, fromOption, and fromEither constructors to convert nullable values, Option, or Either into Effects or Streams.
This enables safe, typeful interop with legacy code, APIs, or libraries that use null, undefined, or their own option/either types.
Converting to Effect, Stream, Option, or Either lets you use all the combinators, error handling, and resource safety of the Effect ecosystem, while avoiding the pitfalls of null and undefined.
import { Effect, Option, Either } from "effect";
// Option: Convert a nullable value to an Option
const nullableValue: string | null = Math.random() > 0.5 ? "hello" : null;
const option = Option.fromNullable(nullableValue); // Option<string>
// Effect: Convert an Option to an Effect that may fail
const someValue = Option.some(42);
const effectFromOption = Option.match(someValue, {
onNone: () => Effect.fail("No value"),
onSome: (value) => Effect.succeed(value),
}); // Effect<number, string, never>
// Effect: Convert an Either to an Effect
const either = Either.right("success");
const effectFromEither = Either.match(either, {
onLeft: (error) => Effect.fail(error),
onRight: (value) => Effect.succeed(value),
}); // Effect<string, never, never>Explanation:
Effect.fromNullablelifts a nullable value into an Effect, failing if the value isnullorundefined.Effect.fromOptionlifts an Option into an Effect, failing if the Option isnone.Effect.fromEitherlifts an Either into an Effect, failing if the Either isleft.
Passing around null, undefined, or custom option/either types without converting them, which leads to unsafe, non-composable code and harder error handling.