40 lines
1.2 KiB
TypeScript
40 lines
1.2 KiB
TypeScript
/**
|
|
* A successful value
|
|
*/
|
|
export declare type Ok<R> = {
|
|
_tag: 'ok';
|
|
value: R;
|
|
};
|
|
/**
|
|
* A failed value
|
|
*/
|
|
export declare type Err<L> = {
|
|
_tag: 'error';
|
|
error: L;
|
|
};
|
|
/**
|
|
* A safe result type: imagine a language with no exceptions — the way to handle
|
|
* errors would be to use something like a tagged union type.
|
|
*
|
|
* Why would we want that? I want to explicitly handle exceptions in this library
|
|
* and having this construct really helps. It's also pretty easy to implement.
|
|
*/
|
|
export declare type Result<L, R> = Err<L> | Ok<R>;
|
|
export declare function ok<O>(value: O): Ok<O>;
|
|
export declare function err<E>(error: E): Err<E>;
|
|
/**
|
|
* Checks whether a value is an `Ok`.
|
|
* Handy with TypeScript guards
|
|
*/
|
|
export declare function isOk<R>(result: Result<any, R>): result is Ok<R>;
|
|
/**
|
|
* Checks whether a value is an `Err`.
|
|
* Handy with TypeScript guards
|
|
*/
|
|
export declare function isErr<L>(either: Result<L, any>): either is Err<L>;
|
|
/**
|
|
* Convert a `Promise<T>` into a `Promise<Result<Error, T>>`,
|
|
* therefore catching the errors and being able to handle them explicitly
|
|
*/
|
|
export declare function safeAsync<O>(promise: Promise<O>): Promise<Result<Error, O>>;
|