everweij / typescript-result

A Result type inspired by Rust and Kotlin that leverages TypeScript's powerful type system to simplify error handling and make your code more readable and maintainable with full type safety.
MIT License
76 stars 5 forks source link

Expose `isResult` helper #2

Closed stalniy closed 4 months ago

stalniy commented 3 years ago

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!

everweij commented 4 months ago

The behavior you describe and wish for is now available in v2.