isResult
Check if a value is a Result tuple
217 bytes
since v12.2.0
Usage
Check if a value is a Result tuple.
Don’t know what that is? Read the Result section further down.
import * as _ from 'radashi'
_.isResult([undefined, 42]) // => true_.isResult([new Error(), undefined]) // => true
// Tuple must be of length 2._.isResult([new Error()]) // => false_.isResult([undefined, true, undefined]) // => false
// Non-tuple values are false._.isResult([]) // => false_.isResult({}) // => false_.isResult(null) // => false
// Result tuples cannot have both a value and an error._.isResult([new Error(), true]) // => falseAlso see the related isResultOk and isResultErr functions.
Types In-Depth
Result
“Results” are tuples of 2 elements (an error and a result value).
- The first element is always the error, or
undefinedif the operation was successful. - The second element is always the result value, unless an error occurred.
- These tuples are represented by the
Result<TResult, TError>type. - A default error type of
Erroris used when no error type is explicitly defined (e.g.Result<string>).
Ok and Err
There are 2 types of result: Ok<TResult> and Err<TError>.
- The
Oktype represents a successful operation. It’s a tuple of[undefined, TResult]. - The
Errtype represents a failed operation. It’s a tuple of[TError, undefined].
The names “Ok” and “Err” are inspired by Rust’s std::result module.
To check for an Ok result, do this:
declare const value: unknown
if (isResult(value) && value[0] == null) { value // <-- now an Ok<unknown> type value[1] // <-- This is the resulting value!}To check for an Err result, do this:
declare const value: unknown
if (isResult(value) && value[0] != null) { value // <-- now an Err<Error> type value[0] // <-- This is the error!}You can also use the isResultOk and isResultErr functions to check for Ok and Err results respectively.