Skip to content

Latest commit

 

History

History
73 lines (58 loc) · 1.98 KB

File metadata and controls

73 lines (58 loc) · 1.98 KB
title Understand the Option Data Type
id data-option
skillLevel beginner
applicationPatternId core-concepts
summary Use Option<A> to explicitly represent a value that may or may not exist, eliminating null and undefined errors.
tags
Option
optional
data-type
domain
effect
rule
description
Use Option to model values that may be present or absent, making absence explicit and type-safe.
related
data-either
data-struct
author PaulJPhilp
lessonOrder 16

Model Optional Values Safely with Option

Guideline

Use the Option<A> data type to represent values that may or may not exist.
This eliminates the need for null or undefined, making absence explicit and type-safe.

Rationale

Option makes it impossible to forget to handle the "no value" case.
It improves code safety, readability, and composability, and is a foundation for robust domain modeling.

Good Example

import { Option } from "effect";

// Create an Option from a value
const someValue = Option.some(42); // Option<number>
const noValue = Option.none(); // Option<never>

// Safely convert a nullable value to Option
const fromNullable = Option.fromNullable(Math.random() > 0.5 ? "hello" : null); // Option<string>

// Pattern match on Option
const result = someValue.pipe(
  Option.match({
    onNone: () => "No value",
    onSome: (n) => `Value: ${n}`,
  })
); // string

// Use Option in a workflow
function findUser(id: number): Option.Option<{ id: number; name: string }> {
  return id === 1 ? Option.some({ id, name: "Alice" }) : Option.none();
}

Explanation:

  • Option.some(value) represents a present value.
  • Option.none() represents absence.
  • Option.fromNullable safely lifts nullable values into Option.
  • Pattern matching ensures all cases are handled.

Anti-Pattern

Using null or undefined to represent absence, or forgetting to handle the "no value" case, which leads to runtime errors and less maintainable code.