Hyperlinkv0.8.0-beta.28

Result

Result.liftPredicateconsteffect/Result.ts:959
<A, B extends A, E>(
  refinement: Refinement<A, B>,
  orFailWith: (a: A) => E
): (a: A) => Result<B, E>
<B extends A, E, A = B>(
  predicate: Predicate<A>,
  orFailWith: (a: A) => E
): (a: B) => Result<B, E>
<A, E, B extends A>(
  self: A,
  refinement: Refinement<A, B>,
  orFailWith: (a: A) => E
): Result<B, E>
<B extends A, E, A = B>(
  self: B,
  predicate: Predicate<A>,
  orFailWith: (a: A) => E
): Result<B, E>

Lifts a value into a Result based on a predicate or refinement.

When to use

Use to construct a Result from a raw value guarded by a predicate or refinement.

Details

  • If the predicate returns true, the value becomes Success<A>
  • If the predicate returns false, orFailWith produces the error for Failure<E>
  • Also accepts a Refinement to narrow the success type
  • Supports both data-first and data-last (piped) usage

Example (Validating a number)

import { pipe, Result } from "effect"

const ensurePositive = pipe(
  5,
  Result.liftPredicate(
    (n: number) => n > 0,
    (n) => `${n} is not positive`
  )
)
console.log(ensurePositive)
// Output: { _tag: "Success", success: 5, ... }
Source effect/Result.ts:95921 lines
export const liftPredicate: {
  <A, B extends A, E>(refinement: Refinement<A, B>, orFailWith: (a: A) => E): (a: A) => Result<B, E>
  <B extends A, E, A = B>(
    predicate: Predicate<A>,
    orFailWith: (a: A) => E
  ): (a: B) => Result<B, E>
  <A, E, B extends A>(
    self: A,
    refinement: Refinement<A, B>,
    orFailWith: (a: A) => E
  ): Result<B, E>
  <B extends A, E, A = B>(
    self: B,
    predicate: Predicate<A>,
    orFailWith: (a: A) => E
  ): Result<B, E>
} = dual(
  3,
  <A, E>(a: A, predicate: Predicate<A>, orFailWith: (a: A) => E): Result<A, E> =>
    predicate(a) ? succeed(a) : fail(orFailWith(a))
)