Hyperlinkv0.8.0-beta.28

Option

Option.flatMapconsteffect/Option.ts:1297
<A, B>(f: (a: A) => Option<B>): (self: Option<A>) => Option<B>
<A, B>(self: Option<A>, f: (a: A) => Option<B>): Option<B>

Applies a function that returns an Option to the value of a Some, flattening the result. Returns None if the input is None.

When to use

Use when you need to chain dependent Option computations where each step may return None.

Details

  • Some → applies f to the value and returns its Option result
  • None → returns None without calling f
  • Equivalent to map followed by flatten

Example (Chaining optional lookups)

import { Option } from "effect"

interface User {
  readonly name: string
  readonly address: Option.Option<{ readonly street: Option.Option<string> }>
}

const user: User = {
  name: "John",
  address: Option.some({ street: Option.some("123 Main St") })
}

const street = user.address.pipe(
  Option.flatMap((addr) => addr.street)
)

console.log(street)
// Output: { _id: 'Option', _tag: 'Some', value: '123 Main St' }
Source effect/Option.ts:12977 lines
export const flatMap: {
  <A, B>(f: (a: A) => Option<B>): (self: Option<A>) => Option<B>
  <A, B>(self: Option<A>, f: (a: A) => Option<B>): Option<B>
} = dual(
  2,
  <A, B>(self: Option<A>, f: (a: A) => Option<B>): Option<B> => isNone(self) ? none() : f(self.value)
)
Referenced by 7 symbols