Skip to content

Latest commit

 

History

History
75 lines (61 loc) · 2.53 KB

File metadata and controls

75 lines (61 loc) · 2.53 KB
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
fromNullable
fromOption
fromEither
constructor
effect
stream
option
either
interop
conversion
rule
description
Use fromNullable, fromOption, and fromEither to lift nullable values, Option, or Either into Effects or Streams for safe, typeful interop.
related
constructor-succeed-some-right
constructor-fail-none-left
author PaulJPhilp
lessonOrder 7

Converting from Nullable, Option, or Either

Guideline

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.

Rationale

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.

Good Example

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.fromNullable lifts a nullable value into an Effect, failing if the value is null or undefined.
  • Effect.fromOption lifts an Option into an Effect, failing if the Option is none.
  • Effect.fromEither lifts an Either into an Effect, failing if the Either is left.

Anti-Pattern

Passing around null, undefined, or custom option/either types without converting them, which leads to unsafe, non-composable code and harder error handling.