Hyperlinkv0.8.0-beta.28

Option

Option.genconsteffect/Option.ts:2525
<Self, K, A>(
  ...args:
    | [self: Self, body: (this: Self) => Generator<K, A, never>]
    | [body: () => Generator<K, A, never>]
): Option<A>

Provides generator-based syntax for Option, similar to async/await but for optional values. Yielding a None short-circuits the generator to None.

When to use

Use when you need generator syntax for a sequence of Option steps that should short-circuit on None.

Details

  • Each yield* unwraps a Some value or short-circuits to None
  • The return value is wrapped in Some
  • No Effect runtime is needed

Example (Sequencing Option computations with generator syntax)

import { Option } from "effect"

const maybeName: Option.Option<string> = Option.some("John")
const maybeAge: Option.Option<number> = Option.some(25)

const person = Option.gen(function*() {
  const name = (yield* maybeName).toUpperCase()
  const age = yield* maybeAge
  return { name, age }
})

console.log(person)
// Output:
// { _id: 'Option', _tag: 'Some', value: { name: 'JOHN', age: 25 } }
generatorsDobind
Source effect/Option.ts:252513 lines
export const gen: Gen.Gen<OptionTypeLambda> = (...args) => {
  const f = args.length === 1 ? args[0] : args[1].bind(args[0])
  const iterator = f()
  let state: IteratorResult<any> = iterator.next()
  while (!state.done) {
    const current = state.value
    if (isNone(current)) {
      return current
    }
    state = iterator.next(current.value as never)
  }
  return some(state.value)
}