neverthrow icon indicating copy to clipboard operation
neverthrow copied to clipboard

Add `this` context support to `safeTry` function

Open yasaichi opened this issue 4 months ago • 1 comments

This PR implements support for passing this context to the generator function in safeTry, following the established pattern already implemented in similar libraries like Effect and typescript-result.

Closes #632

Usage

class MyClass {
  private multiplier = 2;
  
  getValue(): number {
    return 10;
  }
  
  myMethod(): Result<number, string> {
    return safeTry(this, function* () {
      const value = this.getValue();
      return ok(value * this.multiplier);
    });
  }
}

Why This Matters

This feature enhances the ergonomics of safeTry when used in class-based designs, eliminating the need for manual binding to preserve context (e.g. that). This brings neverthrow in line with other modern Result/Effect libraries that have already adopted this pattern.

yasaichi avatar Aug 10 '25 21:08 yasaichi