Skip to content

Conversation

@GregOnNet
Copy link
Contributor

@GregOnNet GregOnNet commented May 24, 2022

This PR proposes two Type-Guards, allowing to safely access error or value of a Result.
This should improve the Ergonomics of the Result-API.

hasValue

// instead of
if (result.isSuccess) {
  const value = result.getValueOrThrow();
}

// do
if (result.hasValue()) {
  const value = result.value; // value is accessible because the type-guard has been executed before
}

hasError

// instead of
if (result.isFailure) {
  const error = result.getErrorOrThrow();
}

// do
if (result.hasError()) {
  const error= result.error; // erroris accessible because the type-guard has been executed before
}

Some notes

  • I needed to introduce two new Methods because Type-Guards are not usable with Getters (reference: Custom type guard in getters is broken microsoft/TypeScript#7150 (comment))
  • Changing the existing getters isSuccess and isFailure to methods would introduce a breaking change.
  • Personally, I would love to use isSuccess() directly. Maybe this could be a breaking change for the next major release.

@seangwright
Copy link
Owner

Thanks for the contribution! I'll get a new release pushed out soon.

@seangwright seangwright closed this Jun 2, 2022
@seangwright seangwright reopened this Jun 2, 2022
@seangwright seangwright merged commit 0bdc72d into seangwright:main Jun 2, 2022
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

Successfully merging this pull request may close these issues.

2 participants