Skip to content

Feature Request: Allow Passing this Context to safeTry #632

@yasaichi

Description

@yasaichi

I would like to propose a feature enhancement for neverthrow's safeTry that enables passing the this context to the function being executed. This change would mimic the interface of effect-ts and allow patterns like the following:

compute = Effect.gen(this, function* () {
  const n = this.local + 1;

  yield* Effect.log(`Computed value: ${n}`);

  return n;
});

See: https://effect.website/docs/getting-started/using-generators/#passing-this

Current Behavior
At the moment, safeTry does not allow the caller to bind the this context, making it difficult to use in object-oriented patterns where instance properties are required inside the callback.

Expected Behavior
The expected behavior is for safeTry to accept an optional this context and invoke the callback with that context. For example, a possible usage could be:

class MyClass {
  mayFail1: () => Result<number, string>;
  mayFail2: () => Result<number, string>;

  myFunc(): Result<number, string> {
    return safeTry<number, string>(this, function* () { // or safeTry<R, L>(function* () { ... }, this)
      return ok(
        (yield* this.mayFail1().mapErr(
          (e) => `aborted by an error from 1st function, ${e}`
        )) +
          (yield* this.mayFail2().mapErr(
            (e) => `aborted by an error from 2nd function, ${e}`
          ))
      );
    });
  }
}

Benefits

  • Enhanced usability: Allowing this binding makes safeTry more versatile, especially when working within class-based structures.
  • Improved integration: This feature would simplify the integration of neverthrow into codebases that rely on object-oriented design and effectful computations.

I would appreciate any feedback on this proposal. Thank you for considering this feature request!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions