Hyperlinkv0.8.0-beta.28

Option

Option.liftPredicateconsteffect/Option.ts:2178
<A, B extends A>(refinement: Refinement<A, B>): (a: A) => Option<B>
<B extends A, A = B>(predicate: Predicate<A>): (b: B) => Option<B>
<A, B extends A>(self: A, refinement: Refinement<A, B>): Option<B>
<B extends A, A = B>(self: B, predicate: Predicate<A>): Option<B>

Lifts a Predicate or Refinement into the Option context: returns Some(value) when the predicate holds, None otherwise.

When to use

Use to convert a boolean check into an Option-returning function

  • Validating input and wrapping it in Option

Details

  • predicate(value) is trueSome(value)
  • predicate(value) is falseNone
  • Supports refinements for type narrowing

Example (Validating positive numbers)

import { Option } from "effect"

const parsePositive = Option.liftPredicate((n: number) => n > 0)

console.log(parsePositive(1))
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

console.log(parsePositive(-1))
// Output: { _id: 'Option', _tag: 'None' }
Source effect/Option.ts:217815 lines
export const liftPredicate: { // Note: I intentionally avoid using the NoInfer pattern here.
  <A, B extends A>(refinement: Refinement<A, B>): (a: A) => Option<B>
  <B extends A, A = B>(predicate: Predicate<A>): (b: B) => Option<B>
  <A, B extends A>(
    self: A,
    refinement: Refinement<A, B>
  ): Option<B>
  <B extends A, A = B>(
    self: B,
    predicate: Predicate<A>
  ): Option<B>
} = dual(
  2,
  <B extends A, A = B>(b: B, predicate: Predicate<A>): Option<B> => predicate(b) ? some(b) : none()
)