Skip to content
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

Switch error-type during chain #30

Open
ComradeVanti opened this issue Mar 11, 2024 · 0 comments
Open

Switch error-type during chain #30

ComradeVanti opened this issue Mar 11, 2024 · 0 comments

Comments

@ComradeVanti
Copy link

Let's say I have the following result:

const result: Result<number, ErrorA> = someOperation();

and I want to chain like this:

// Assuming ErrorA and ErrorB are structurally different.
result.chain(value => {
  if(value < 0) return err(new ErrorB());
  else return ok(value);
});

then I get the error:

TS2345: Argument of type (value: number) => Result<number, ErrorA> | Result<never, ErrorB> is
  not assignable to parameter of type (value: number) => Result<number, ErrorA>
Type Result<number, ErrorA> | Result<never, ErrorB> is not assignable to type 
  Result<number, ErrorA>
Type Ok<never, ErrorB> is not assignable to type Result<number, ErrorA>
Type Ok<never, ErrorB> is not assignable to type Ok<number, ErrorA>
Property x is missing in type ErrorB but required in type ErrorA

It seems like it is not possible to switch error type inside a chain with only a ok-mapper. The only workaround is:

result.chain<number, ErrorA | ErrorB>(
  (value) => {
    if (value < 0) return err(new ErrorB());
    else return ok(value);
  },
  (error) => err(error)
);

but that is clearly too verbose.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant