effect-io-ai

Package: effect
Module: Optic

Optic.makeOptional

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

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

See

Signature

declare const makeOptional: <S, A>(getResult: (s: S) => Result.Result<A, string>, set: (a: A, s: S) => Result.Result<S, string>) => Optional<S, A>

Source

Since v4.0.0