Hyperlinkv0.8.0-beta.28

Optic

Optic.makeOptionalfunctioneffect/Optic.ts:986
<S, A>(
  getResult: (s: S) => Result.Result<A, string>,
  set: (a: A, s: S) => Result.Result<S, string>
): Optional<S, A>

Creates an Optional from a fallible getter and a fallible setter.

When to use

Use when you need an optic for a focus that may be missing on read and may reject updates on write.

Details

  • getResult should return Result.fail(message) on mismatch.
  • set should return Result.fail(message) when the update cannot be applied.

Example (Accessing record keys safely)

import { Optic, Result } from "effect"

const atKey = (key: string) =>
  Optic.makeOptional<Record<string, number>, number>(
    (s) =>
      Object.hasOwn(s, key)
        ? Result.succeed(s[key])
        : Result.fail(`Key "${key}" not found`),
    (a, s) =>
      Object.hasOwn(s, key)
        ? Result.succeed({ ...s, [key]: a })
        : Result.fail(`Key "${key}" not found`)
  )

console.log(Result.isSuccess(atKey("x").getResult({ x: 1 })))
// Output: true
Source effect/Optic.ts:9866 lines
export function makeOptional<S, A>(
  getResult: (s: S) => Result.Result<A, string>,
  set: (a: A, s: S) => Result.Result<S, string>
): Optional<S, A> {
  return make(new OptionalNode(getResult, set))
}