Make E generic Throwable in attempt function#15
Make E generic Throwable in attempt function#15joelbutcher wants to merge 4 commits intofix/attempt-throwable-genericfrom
attempt function#15Conversation
There was a problem hiding this comment.
Pull request overview
This PR modifies the attempt helper function to make its error type parameter E generic (bounded by Throwable) instead of fixed to Throwable. This change aims to allow developers to specify more precise exception types in their return type annotations, enabling better type inference in downstream code when using methods like match or orElse.
Key changes:
- Added
@template E of Throwableto theattemptfunction's PHPDoc - Changed return type annotation from
Result<T, Throwable>toResult<T, E>
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
src/Result/functions.php
Outdated
| * @template E of Throwable | ||
| * @param callable(): T $f | ||
| * @return Result<T, Throwable> | ||
| * @return Result<T, E> |
There was a problem hiding this comment.
The addition of @template E of Throwable with return type Result<T, E> introduces a type soundness concern. Since PHPStan cannot infer E from the callable parameter (which has no exception specification), and the function body catches all Throwable exceptions, this allows potentially incorrect type narrowing.
For example:
/** @return Result<int, RuntimeException> */
function foo(): Result {
// Type checks, but could throw LogicException
return attempt(fn() => throw new LogicException());
}While this pattern allows developers to manually specify exception types they know their code throws (via type hints or annotations), it shifts the responsibility for correctness from the type system to the developer.
Consider adding a documentation comment explaining that developers must ensure their callable only throws exception types compatible with their declared return type, or consider keeping the original @return Result<T, Throwable> for guaranteed type safety.
This PR makes the E passed to the Result PHP return doc for the
attempthelper function a generic of type Throwable, allowing for improved PHPStan reporting with functions that already return typedResults in PHP doc:This will fix handling
matchororElsecalls where strongly typing the known exception type in the passed closure is preferred overfn(Throwable $t) => handler(...)