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 } 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();