Skip to main content
The Option data type represents optional values, providing a type-safe alternative to null or undefined.

Type Signature

type Option<A> = Some<A> | None<A>

interface Some<A> {
  readonly _tag: "Some"
  readonly value: A
}

interface None<A> {
  readonly _tag: "None"
}

Creating Options

import { Option } from "effect"

const value = Option.some(42)
// Option<number>

console.log(value)
// { _id: 'Option', _tag: 'Some', value: 42 }

Type Guards

import { Option } from "effect"

const value = Option.some(1)

if (Option.isSome(value)) {
  console.log(value.value)  // 1
}

if (Option.isNone(value)) {
  console.log("No value")
}

Pattern Matching

match

Handle both Some and None cases.
import { Option } from "effect"

const foo = Option.some(1)

const message = Option.match(foo, {
  onNone: () => "Option is empty",
  onSome: (value) => `Option has a value: ${value}`
})

console.log(message)
// "Option has a value: 1"

Extracting Values

import { Option } from "effect"

const value = Option.some(1).pipe(
  Option.getOrElse(() => 0)
)
// 1

const none = Option.none().pipe(
  Option.getOrElse(() => 0)
)
// 0

Transformations

map

import { Option } from "effect"

const result = Option.some(2).pipe(
  Option.map(n => n * 2)
)
// Some(4)

flatMap

import { Option } from "effect"

const result = Option.some(2).pipe(
  Option.flatMap(n => n > 0 ? Option.some(n * 2) : Option.none())
)
// Some(4)

filter

import { Option } from "effect"

const result = Option.some(5).pipe(
  Option.filter(n => n > 3)
)
// Some(5)

const filtered = Option.some(2).pipe(
  Option.filter(n => n > 3)
)
// None

Conversions

import { Option } from "effect"

Option.toArray(Option.some(1))  // [1]
Option.toArray(Option.none())   // []

Combining Options

zipWith

import { Option } from "effect"

const result = Option.zipWith(
  Option.some(2),
  Option.some(3),
  (a, b) => a + b
)
// Some(5)

orElse

import { Option } from "effect"

const result = Option.none().pipe(
  Option.orElse(() => Option.some(42))
)
// Some(42)
Option is ideal for representing values that may or may not exist, eliminating null pointer errors and making optionality explicit in your type signatures.

Common Use Cases

  • Initial values for configurations
  • Optional fields in data structures
  • Results from partial functions (functions not defined for all inputs)
  • Safe null handling without exceptions

Key Operations

OperationDescription
someCreates an Option containing a value
noneCreates an empty Option
fromNullableConverts nullable values to Option
isSomeChecks if Option contains a value
isNoneChecks if Option is empty
matchPattern match on Option
getOrElseExtracts value or returns default
mapTransforms the contained value
flatMapChains Option-returning operations
filterFilters based on a predicate

Build docs developers (and LLMs) love