The Either type uses type guards to enforce error handling before allowing access to a return value. Use it when a function may return either an Error or a result.
console.log(result.error);// .error property available
}else{
console.log(result.value);// .value property available
}
Typed Errors with ErrorResult<T>
Sometimes a function can return an Error. The ErrorResult type can wrap an Error, and provides metadata on the type of error, allowing you to communicate to consuming code the types of error that can be returned.
You don't have to use it, in which case just use ErrorResult<Error> everywhere.
If you do want error typings, then you need to create wrappers for errors.
For example, if your code can return a NotImplementedError or a ValidationError, then you declare classes for each of these Error types, extending Error. Then you can specify part of your return as ErrorResult<NotImplementedError | ValidationError>.
You need to implement your typed errors so that you can test them in consuming code using instanceof. So:
Then in the consuming code you can test the ErrorResult like this:
constresult=errorOrResult();
if(result.isError){
if(result.errorinstanceofNotImplementedError){
// NotImplementedError
}else{
// ValidationError
}
}else{
console.log(result.value);
}
Maybe
The Maybe type uses type guards to enforce handling an undefined or null value before accessing the value. Use it when a function return value maybe null or undefined.