This container represents either a result value or an error value. You can create a Result<T, E>
by calling either of the following constructors:
Ok('Hello world')
Err('Failure')
- Result.ok, Result.result and Result.error
- Result.map()
- Result.unwrap()
- Result.unwrapOr()
- Result.asOption()
Result.ok
is used to check if a Result<R, E>
is a success or failure.
- If
Result.ok === true
, thenResult.result
exists. - If
Result.ok === false
, thenResult.error
exists.
TODO
Map Result<T, E>
into a new Result<U, E>
.
.map()
is used to continue work on results, regardless of if they contain an error or a result.
const helloWorld = new Ok("Hello world");
// Converts Ok("Hello world") → Ok(11)
const helloWorldLength = helloWorld.map(helloStr => helloStr.length);
// Outputs 'Ok(11)'
console.log(helloWorldLength);
Returns the success value T
of Result<T, E>
. Throws if result is an error.
In general, because this function may throw, use of .unwrap() use is discouraged. Instead, prefer to use an if statment and check .ok and handle the Err
case explicitly.
.unwrap()
can be used when you are sure thatResult
is successful. Use at own risk..unwrap()
can be used when writing prototypes of software and then refactored later into proper error handling.
const helloWorld = new Ok("Hello world");
// Outputs 'Hello world'
console.log(helloWorld.unwrap());
Returns the success value T
of Result<T, E>
if any, otherwise a default value.
const helloWorld = new Ok("Hello World");
const error = new Err("Failure");
// Outputs 'Hello World'
console.log(helloWorld.unwrapOr("Hello Vertical"));
// Outputs 'Hello Vertical'
console.log(error.unwrapOr("Hello Vertical"));
Discards the error value of Result<T, E>
and return Option<T>
.
.asOption()
is useful if you don't care about the error value and want to simplify toOption<T>
const helloWorld = new Ok("Hello World");
const error = new Err("Failure");
// Outputs 'Some("Hello World")'
console.log(helloWorld.asOption());
// Outputs 'None()'
console.log(error.asOption());
import { Result, Ok, Err } from "containers-ts";
function toNumber(s: string): Result<number, string> {
const number = Number(s);
if (isNaN(number)) {
return new Err("String does not contain a number");
}
return new Ok(number);
}
function addToString(s: string, n: number): Result<string, string> {
return toNumber("4").map(n => String(n + 1));
}
// Outputs: Ok("8")
console.log(addToString("4", 4));
// Outputs: Err("String does not contain a number")
console.log(addToString("Vertical Strategy", 4));