twitten
Version:
A fluent js/ts implementation of the result monad, utilizing Happy/Sad path terminology.
79 lines (78 loc) • 2.96 kB
TypeScript
export declare namespace Sync {
type Happy<T> = T;
type Sad = Error;
type Outcome<T> = Happy<T> | Sad;
/**
* @class An implementation of the result monad, utilizing Happy/Sad path terminiology.
*/
class Path<T> {
/**
*@description a discriminated union that holds the value or error of the `Path`.
*/
readonly outcome: Outcome<T>;
private constructor();
/**
* Factory method for creating an instance of the `Path` class with a value.
* @param value is the success value of the happy path.
*/
static happy<T>(value: T): Path<T>;
/**
* @description A happy path continuation.
* @param callback a function that is executed only when the `outcome` of `Path` is happy.
* @returns an instance of `Path<TNewValue>` where `TNewValue` is the return type of `continuation`.
*/
onHappyPath<TNewValue>(callback: (value: T) => TNewValue): Path<TNewValue>;
/**
* A helper function for type-checking an `Outcome`.
* @param outcome the `outcome` of a `Path`.
* @remark an alternative to using continuations.
*/
isHappy<T>(outcome: Happy<T> | Sad): outcome is Happy<T>;
/**
* A Factory method for creating an instance of the `Path` class with an error.
* @param error is the error of the sad path.
*/
static sad<T>(error: Error): Path<T>;
/**
* @param callbackWithParam a function that is executed only when the `outcome` of `Path` is sad.
*/
onSadPath(callbackWithParam: (error: Error) => void): Path<T>;
/**
* @param callback a function that is executed only when the `outcome` of `Path` is sad.
*/
onSadPath(callback: () => void): Path<T>;
/**
* A helper function for type-checking an `Outcome`.
* @param outcome the `outcome` of a `Path`.
* @remark an alternative to using continuations.
*/
isSad(outcome: Sad | Happy<T>): outcome is Sad;
}
}
/**
* @description A Wrapper around path, so that happy paths can be created more fluent.
* @example Happy.path(<value>);
*/
export declare const Happy: {
path: typeof Sync.Path.happy;
};
/**
* @description A Wrapper around path, so that sad paths can be created more fluent.
* @example Sad.path(<error>);
*/
export declare const Sad: {
path: typeof Sync.Path.sad;
};
export declare namespace Async {
/**
* @description Wrapper around `Promise<T>`
*/
class Path<T> {
private readonly promise;
private constructor();
static fromPromise<T>(promise: Promise<T>): Path<T>;
onHappyPath<TNewValue>(callback: (value: T) => TNewValue): Path<TNewValue>;
onSadPath(callbackWithParam: (error: Error) => void): Path<T>;
onSadPath(callback: () => void): Path<T>;
}
}