Option<T>

Safe handling of nullable values

Replace null/undefined checks with a type-safe container that forces explicit handling

What is Option<T>?

Option is a container that either holds a value (Some) or represents the absence of a value (None). It eliminates null pointer exceptions by making nullable values explicit in the type system.

// Create options
const value = Option("hello") // Some("hello")
const empty = Option(null) // None

// Transform values
const upper = value.map((s) => s.toUpperCase()) // Some("HELLO")
const _nothing = empty.map((s) => s.toUpperCase()) // None

// Chain operations
const result = value
  .map((s) => s.length)
  .filter((len) => len > 3)
  .getOrElse(0) // 5

// Pattern matching
const message = value.fold(
  () => "No value",
  (s) => `Value: ${s}`,
) // "Value: hello"

Key Features

Type Safety

TypeScript enforces explicit handling of empty cases, preventing runtime null errors

Chainable Operations

map, flatMap, filter - transform values without null checks

Pattern Matching

Explicit Some/None handling with fold() and match()

Composable

Works seamlessly with Do-notation for complex workflows

Common Patterns

Creating Options

Option(42) // Some(42)
Option(null) // None
Option(undefined) // None
Option.none() // Explicitly create None

Transforming Values

const doubled = Option(5)
  .map((x) => x * 2) // Some(10)
  .filter((x) => x > 5) // Some(10)
  .getOrElse(0) // 10

Pattern Matching

const option = Option("test")
option.match({
  Some: (value) => `Found: ${value}`,
  None: () => "Not found",
})

When to Use Option

Function return values that might not exist

Database queries, array searches, user input parsing

Optional configuration or parameters

Default values, optional fields in objects

Chaining operations where any step might fail

Validation pipelines, data transformations