import { Result } from "https://deno.land/x/rusty_result@0.1.1/mod.ts";
Typescript implementation of Rust Result type.
// Create an ok Result
const myOkResult = Result.ok(1);
// Create an error Result
const myErrorResult = Result.error(2);
// Create a Result with an explicit ok and error type
const r = Result.error<number, number>(3);
// Create a function that takes Results
function myResultFunction(r: Result<number, number>): void {
// Perform operation on ok value and get new Result
const r2 = r.map((x) => x + 10);
// Perform operation on ok value and on error value and get new Result
const r3 = r.map((x) => x + 10).mapError((x) => x - 10);
// Do action if Result is ok
if (r3.isOk()) {
console.log(`r3 is ok with value of: ${r3.unwrap()}`);
}
// Do action if Result is error
if (r3.isError()) {
console.log(`r3 is error with value of: ${r3.unwrapError()}`);
}
}
// Use Result with a function
myResultFunction(r); // prints: r3 is error with value of: -7
Methods
Get "ok" value or throw error. Note in the "empty case" that type Ok
is void
then
undefined
is returned.
unwrapError(): Error
Get "error" value or throw error. Note in the "empty case" that type Error
is void
then
undefined
is returned.
Static Methods
Create "error" value representing failure with error result. This can be used to create an error Result with a value or without one.
const myStringResult = Result.error('bar')
const myEmptyResult = Result.error()