Safe handling of nullable values
Replace null/undefined checks with a type-safe container that forces explicit handling
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"
TypeScript enforces explicit handling of empty cases, preventing runtime null errors
map, flatMap, filter - transform values without null checks
Explicit Some/None handling with fold() and match()
Works seamlessly with Do-notation for complex workflows
Option(42) // Some(42)
Option(null) // None
Option(undefined) // None
Option.none() // Explicitly create None
const doubled = Option(5)
.map((x) => x * 2) // Some(10)
.filter((x) => x > 5) // Some(10)
.getOrElse(0) // 10
const option = Option("test")
option.match({
Some: (value) => `Found: ${value}`,
None: () => "Not found",
})
Database queries, array searches, user input parsing
Default values, optional fields in objects
Validation pipelines, data transformations