Skip to content

Switch error-type during chain #30

Description

@ComradeVanti

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions