typescript-result icon indicating copy to clipboard operation
typescript-result copied to clipboard

Returning Result.error from AsyncResult type functions?

Open pjeziorowski opened this issue 9 months ago • 1 comments

Currently when you try to do something like this:

  forgotPassword(
    data: ForgotPasswordDTO
  ): AsyncResult<void, ValidationException | PersistenceException | UnexpectedError> {
    if (...) {
      return Result.error(new UnexpectedError('Something went wrong'))
    }
...

you'll see an error:

Type 'Result<never, UnexpectedError>' is missing the following properties from type 'AsyncResult<void, ValidationException | PersistenceException | UnexpectedError>': isAsyncResult, then, catch, finally, [Symbol.toStringTag]ts(2

I think returning Result.error() should work fine in functions that return AsyncResult as long as the error type adheres to the function type? 🤔

pjeziorowski avatar Feb 25 '25 16:02 pjeziorowski

Currently my workaround is something like this:

      return Result.fromAsync(Promise.resolve(Result.error(new UserNoPassword(this.id))))

which is quite verbose

pjeziorowski avatar Feb 25 '25 16:02 pjeziorowski

Hey @pjeziorowski how's it going? In your case, using just AsyncResult.error() shouldn't do the job?

  forgotPassword(
    data: ForgotPasswordDTO
  ): AsyncResult<void, ValidationException | PersistenceException | UnexpectedError> {
    if (...) {
      return AsyncResult.error(new UnexpectedError('Something went wrong'))
    } 
}

jmartins-sh avatar Apr 19 '25 01:04 jmartins-sh

@jmartins-sh just looking at the source code in master right now and AsyncResult.error is marked as @internal and therefor not exposed to the public API. I am getting the same problem as @pjeziorowski and unsure how you were able to use AsyncResult.error.

hazzery avatar Jun 02 '25 07:06 hazzery

Hi, I am working on a solution for this. I'm testing a couple of final things myself and plan to release this functionality, along with some other improvements, in the coming days. You can preview it here: https://github.com/everweij/typescript-result/tree/next?tab=readme-ov-file#async-operations / https://github.com/everweij/typescript-result/releases/tag/v3.2.0-beta.6

@pjeziorowski this means you can do this:

forgotPassword(data: ForgotPasswordDTO) {
    return Result.fromAsync(async () => {

        await someAsyncCode();

        if (...) {
            return Result.error(new UnexpectedError('Something went wrong'))
        } 
    });
}

everweij avatar Jul 01 '25 07:07 everweij

Just released: https://github.com/everweij/typescript-result/releases/tag/v3.2.0

everweij avatar Jul 03 '25 16:07 everweij