ts-results
A typescript implementation of Rust's Result object.
Installation
$ npm install ts-results
or
$ yarn install ts-results
Usage
import { Result, Err, Ok, Results } from 'ts-results';
Creation
let okResult: Result<number, Error> = Ok(10);
let okResult2 = Ok<number, Error>(10);
let errorResult: Result<number, Error> = Ok(new Error('bad number!'));
let errorResult2 = Ok<number, Error>(new Error('bad number!'));
Type Safety
let result = Ok<number, Error>(1);
if (result.ok) {
let number = result.val + 1;
} else {
console.error(result.val.message);
}
if (result.err) {
console.error(result.val.message);
} else {
let number = result.val + 1;
}
Unwrap
let goodResult = Ok<number, Error>(1);
let badResult = Err<number, Error>(new Error("something went wrong"));
goodResult.unwrap();
badResult.unwrap();
Expect
let goodResult = Ok<number, Error>(1);
let badResult = Err<number, Error>(new Error("something went wrong"));
goodResult.expect('goodResult should be a number');
badResult.expect('badResult should be a number');
Map
let goodResult = Ok<number, Error>(1);
let badResult = Err<number, Error>(new Error("something went wrong"));
goodResult.map(num => num + 1).unwrap();
badResult.map(num => num + 1).unwrap();
goodResult.map(num => num + 1, err => new Error('mapped')).unwrap();
badResult.map(num => num + 1, err => new Error('mapped')).unwrap();
goodResult.map(null, err => new Error('mapped')).unwrap();
badResult.map(null, err => new Error('mapped')).unwrap();
Else
let goodResult = Ok<number, Error>(1);
let badResult = Err<number, Error>(new Error("something went wrong"));
goodResult.else(5);
badResult.else(5);
Combining Results
There may be some cases where we have two or more separate Result
objects and we want to do something with both values.
This is handled by using the Results
function to combine them.
let pizzaResult: Result<Pizza, GetPizzaError> = getPizzaSomehow();
let toppingsResult: Result<Toppings, GetToppingsError> = getToppingsSomehow();
let result = Results(pizzaResult, toppingsResult);
let [pizza, toppings] = result.unwrap();