result icon indicating copy to clipboard operation
result copied to clipboard

Switch error-type during chain

Open ComradeVanti opened this issue 4 months ago • 0 comments

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.

ComradeVanti avatar Mar 11 '24 16:03 ComradeVanti