Package: effect
Module: Effect
Filters an effect, failing with a custom error if the predicate fails.
Details
This function applies a predicate to the result of an effect. If the
predicate evaluates to false, the effect fails with a custom error
generated by the orFailWith function.
When to Use
This is useful for enforcing constraints and treating violations as recoverable errors.
Providing a Guard
In addition to the filtering capabilities discussed earlier, you have the option to further refine and narrow down the type of the success channel by providing a user-defined type guard. Let’s explore this concept through an example:
Example
import { Effect, pipe } from "effect"
// Define a user interface
interface User {
readonly name: string
}
// Simulate an asynchronous authentication function
declare const auth: () => Promise<User | null>
const program = pipe(
Effect.promise(() => auth()),
// Use filterOrFail with a custom type guard to ensure user is not null
Effect.filterOrFail(
(user): user is User => user !== null, // Type guard
() => new Error("Unauthorized")
),
// 'user' now has the type `User` (not `User | null`)
Effect.andThen((user) => user.name)
)
Signature
declare const filterOrFail: { <A, E2, B extends A>(refinement: Refinement<NoInfer<A>, B>, orFailWith: (a: EqualsWith<A, B, NoInfer<A>, Exclude<NoInfer<A>, B>>) => E2): <E, R>(self: Effect<A, E, R>) => Effect<NoInfer<B>, E2 | E, R>; <A, E2>(predicate: Predicate<NoInfer<A>>, orFailWith: (a: NoInfer<A>) => E2): <E, R>(self: Effect<A, E, R>) => Effect<A, E2 | E, R>; <A, E, R, E2, B extends A>(self: Effect<A, E, R>, refinement: Refinement<A, B>, orFailWith: (a: EqualsWith<A, B, A, Exclude<A, B>>) => E2): Effect<NoInfer<B>, E2 | E, R>; <A, E, R, E2>(self: Effect<A, E, R>, predicate: Predicate<A>, orFailWith: (a: A) => E2): Effect<A, E2 | E, R>; <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): <E, R>(self: Effect<A, E, R>) => Effect<NoInfer<B>, Cause.NoSuchElementException | E, R>; <A>(predicate: Predicate<NoInfer<A>>): <E, R>(self: Effect<A, E, R>) => Effect<A, Cause.NoSuchElementException | E, R>; <A, E, R, B extends A>(self: Effect<A, E, R>, refinement: Refinement<A, B>): Effect<NoInfer<B>, E | Cause.NoSuchElementException, R>; <A, E, R>(self: Effect<A, E, R>, predicate: Predicate<A>): Effect<A, E | Cause.NoSuchElementException, R>; }
Since v2.0.0