New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
orElse should accept new Ok types #411
Comments
Here is a generalized example of a very common use case for me: function foo(): ResultAsync<string, Error> {
return okAsync("string");
}
class FooError extends Error {}
class BarError extends Error {}
function test1() {
return foo().orElse((e) => {
if (e instanceof BarError) {
// Handle the error. Change the OK type.
return okAsync(null);
}
if (e instanceof FooError) {
// Handle the error. Keep the OK type.
return okAsync("foo");
}
// Let the error pass through.
return errAsync(e);
});
}
function test2() {
const intermediateVariable: ResultAsync<string | null, Error> = foo();
return intermediateVariable.orElse((e) => {
if (e instanceof BarError) {
// Handle the error. Change the OK type.
return okAsync(null);
}
if (e instanceof FooError) {
// Handle the error. Keep the OK type.
return okAsync("foo");
}
// Let the error pass through.
return errAsync(e);
});
}
Another workaround is to write a helper function that allows me to work with export function manipulateResultAsync<T1, E1, T2, E2>(
ra: ResultAsync<T1, E1>,
callback: (r: Result<T1, E1>) => Result<T2, E2>
): ResultAsync<T2, E2> {
return new ResultAsync((async () => callback(await ra))());
} Then I can do this: function test3() {
return manipulateResultAsync(foo(), (r) => {
if (r.isOk()) {
return r;
}
const e = r.error;
if (e instanceof BarError) {
// Handle the error. Change the OK type.
return ok(null);
}
if (e instanceof FooError) {
// Handle the error. Keep the OK type.
return ok("foo");
}
// Let the error pass through.
return err(e);
});
} None of this is elegant. |
Current signature:
Suggested signature:
Example scenario:
Current workaround:
The text was updated successfully, but these errors were encountered: