typescript-result
typescript-result copied to clipboard
Returning Result.error from AsyncResult type functions?
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? 🤔
Currently my workaround is something like this:
return Result.fromAsync(Promise.resolve(Result.error(new UserNoPassword(this.id))))
which is quite verbose
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 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.
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'))
}
});
}
Just released: https://github.com/everweij/typescript-result/releases/tag/v3.2.0