Result
A utility class for handling the result of an operation that may succeed or fail. Usage
Create a new instance of the Result class by calling the ok or fail static methods. The ok method creates an instance with a successful result, while the fail method creates an instance with a failed result.
import Result from './result'
const success = Result.ok(1) const failure = Result.fail(new Error('Something went wrong'))
You can then use the instance methods to handle the result. The map method can be used to transform a successful result, while the catch method can be used to handle a failed result.
const doubled = success.map((value) => value * 2) const message = failure.catch((error) => error.message)
The unwrap method can be used to extract the value from a successful result, while the wrap method returns an object with the properties ok and fail, representing the successful and failed results respectively.
const value = success.unwrap() // 1 const wrapped = failure.wrap() // { ok: undefined, fail: Error: Something went wrong }
The toString method returns a string representation of the result, and the toJSON method returns the wrapped result.
console.log(success.toString()) // { ok: 1, fail: undefined } console.log(failure.toJSON()) // { ok: undefined, fail: Error: Something went wrong }
Types
The Result class is generic, and the type of the successful and failed results can be specified.
const success = Result.ok(1) const failure = Result.fail(new Error('Something went wrong'))
TWrap
interface TWrap { ok: T | undefined, fail: Error | undefined }
API constructor
constructor(value: T | undefined, error: Error | undefined) static ok(value: T): Result
Create a new instance of the Result class with a successful result. static fail(error: Error | string): Result
Create a new instance of the Result class with a failed result. map(onFulfilled: (value: T) => U): Result | Result
Transform a successful result. catch(onRejected: (error: Error) => U): Result | Result
Handle a failed result. unwrap(): T | unknown
Extract the value from a successful result. wrap(): TWrap
Return an object with the properties ok and fail, representing the successful and failed results respectively. toString(): string
Return a string representation of the result. toJSON(): TWrap
Return the wrapped result.