Object contains pattern matching functions for an Result.
This object should be sent as argument to the Result.match method.
Creates a Result containing error value.
Note: If you want strong typing define the Result
type for variable the Result
will be
assigned, otherwise it will be Result<any, T>
;
const x: Result<number, string> = Err('something went wrong');
assert(x instanceof Result);
assert.equal(x.unwrapErr(), 'something went wrong');
Creates a Result containing success value.
Note: If you want strong typing define the Result
type for variable the Result
will be
assigned, otherwise it will be Result<T, any>
;
const x: Result<number, string> = Ok(10);
assert(x instanceof Result);
assert.equal(x.unwrap(), 10);
Generated using TypeDoc
Result is the type used for returning and propagating errors. It is a structure with the variants, Ok, representing success and containing a value, and Err, representing error and containing an error value. Functions return Result whenever errors are expected and recoverable.
A simple function returning Result might be defined and used like so:
enum Version { Version1, Version2 } function parseVersion(header: [number]): Result<Version, string> { switch (header[0]) { case undefined: return Err('invalid header length'); case 1: return Ok(Version.Version1); case 2: return Ok(Version.Version2); default: return Err('invalid version'); } } let version = parseVersion([1, 2, 3, 4]); version.match({ Ok: v => console.log(`working with version: ${v}`), Err: e => console.log(`error parsing header: ${e}`), });
Pattern matching on Results is clear and straightforward for simple cases, but Result comes with some convenience methods that make working with it more succinct.
const goodResult: Result<number, number> = Ok(10); const badResult: Result<number, number> = Err(10); // The `isOk` and `isErr` methods do what they say. assert(goodResult.isOk && !goodResult.isErr); assert(badResult.isErr && !badResult.isOk); // `map` consumes the `Result` and produces another. const goodResult2: Result<number, number> = goodResult.map(i => i + 1); const badResult2: Result<number, number> = badResult.map(i => i - 1); // Use `andThen` to continue the computation. const goodResult3: Result<boolean, number> = goodResult2.andThen(i => Ok(i === 11)); // Use `orElse` to handle the error. const badResult3: Result<number, number> = badResult2.orElse(i => Ok(i + 20)); // Consume the result and return the contents with `unwrap`. const finalAwesomeResult = goodResult3.unwrap();