typescript-result icon indicating copy to clipboard operation
typescript-result copied to clipboard

Expose `isResult` helper

Open stalniy opened this issue 4 years ago • 0 comments

Sometimes, I use SomeType | Result<Error, SomeType> as a parameter to function and I don't have a reliable way to check that value is a Result. To write code like this:

function doSomething(value: CustomType | Result<Error, CustomType>) {
  let type: SomeType;

  if (isCustomType(value)) {
     type = value;
  } else if (isResult(value)) {
     if (value.isFailure()) {
        return value;
     }
     type = value.value;
  } else {
    return Result.error(new Error(`Unexpected value ${value}`));
  }

  // some other logic
}

Or maybe something like isFailure(result) and isSuccess(result) would be more helpful, so I could write without nesting:

function doSomething(value: CustomType | Result<Error, CustomType>) {
  let type: SomeType;

  if (isCustomType(value)) {
     type = value;
  } else if (isSuccess(value)) {
     type = value.value;
  } else if (isFailure(value)) {
     return value;
  } else {
    return Result.error(new Error(`Unexpected value ${value}`));
  }

  // some other logic
}

By the way, very nice library! I enjoy using it, thanks!

stalniy avatar Dec 24 '20 14:12 stalniy