seangwright / typescript-functional-extensions

A TypeScript implementation of the C# library CSharpFunctionalExtensions, including synchronous and asynchronous Maybe and Result monads.
MIT License
33 stars 4 forks source link

feat(Result): Expose value or error if it is save to expose #10

Closed GregOnNet closed 2 years ago

GregOnNet commented 2 years ago

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

seangwright commented 2 years ago

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