Type Alias SyncEffect<T, E>

SyncEffect<T, E>: {
    flatMap<U, F>(fn: ((value: T) => SyncEffect<U, F>)): SyncEffect<U, E | F>;
    map<U>(fn: ((value: T) => U)): SyncEffect<U, E>;
    recover<U>(fn: ((error: E) => U)): SyncEffect<T | U, never>;
    run(): Result<T, E>;
}

Represents a deferred computation that can fail safely. It encapsulates a lazy computation that may throw an error, allowing safe composition.

Type Parameters

  • T

    The type of the successful value.

  • E = unknown

    The type of the error.

Type declaration

  • flatMap:function
    • Chains another effect-producing function, allowing error propagation.

      Type Parameters

      • U

        The type of the next computation's success value.

      • F

        The type of the new error that may occur.

      Parameters

      Returns SyncEffect<U, E | F>

      • A new SyncEffect<U, E | F> propagating errors.
      const effect = SyncEffect(() => 10).flatMap(x => SyncEffect(() => x + 5));
      console.log(effect.run()); // Ok(15)
  • map:function
    • Transforms the successful result of the effect.

      Type Parameters

      • U

        The transformed value type.

      Parameters

      • fn: ((value: T) => U)

        Function to apply on success.

          • (value): U
          • Parameters

            • value: T

            Returns U

      Returns SyncEffect<U, E>

      • A new SyncEffect<U, E> with transformed data.
      const effect = SyncEffect(() => 10).map(x => x * 2);
      console.log(effect.run()); // Ok(20)
  • recover:function
    • Recovers from errors by mapping them to a successful value.

      Useful for handling failures gracefully.

      Type Parameters

      • U

      Parameters

      • fn: ((error: E) => U)

        Function to handle errors and return a fallback value.

          • (error): U
          • Parameters

            • error: E

            Returns U

      Returns SyncEffect<T | U, never>

      • A new SyncEffect<T, never> that ensures success.
      const effect = SyncEffect(() => { throw new Error("Boom!"); }).recover(() => 0);
      console.log(effect.run()); // Ok(0)
  • run:function
    • Runs the effect and returns a Result<T, E>.

      Returns Result<T, E>

      • A safe Result, encapsulating success (Ok<T>) or failure (Err<E>).
      const effect = SyncEffect(() => {
      if (Math.random() > 0.5) throw new Error("Failure");
      return 42;
      });
      console.log(effect.run()); // Either Ok(42) or Err(Error)