functional-try
Version:
Error handling wrapper for cleaner use of strict type checking in TypeScript
36 lines (35 loc) • 1.68 kB
TypeScript
export declare namespace FunctionalTry {
type FailableReturnSuccess<TValue> = {
readonly success: true;
readonly failure: false;
readonly value: TValue;
readonly error: undefined;
};
type FailableReturnFailure<TError = Error> = {
readonly success: false;
readonly failure: true;
readonly value: undefined;
readonly error: TError;
};
type FailableReturn<TValue, TError = Error> = FailableReturnSuccess<TValue> | FailableReturnFailure<TError>;
function createSuccess<TValue, TError>(value: TValue): FailableReturn<TValue, TError>;
function createFailure<TValue, TError>(error: TError): FailableReturn<TValue, TError>;
/**
* Safely executes a function and returns the resulting value or error
*
* @param func The function to execute
* @param args The arguments to pass to the function
* @returns A `FailableReturn` with the function's return value or thrown error
*/
function trySync<A extends unknown[], TValue, TError = Error>(func: (...args: A) => TValue, ...args: A): FailableReturn<TValue, TError>;
/**
* Wraps a promise and returns the resulting value or error
*
* @param promise The promise to handle
* @returns A `FailableReturn` with the promise's resulting value or error
*/
function tryAsync<TValue, TError = Error>(promise: Promise<TValue>): Promise<FailableReturn<TValue, TError>>;
}
export type FailableReturn<TValue, TError = Error> = FunctionalTry.FailableReturn<TValue, TError>;
export declare const trySync: typeof FunctionalTry.trySync;
export declare const tryAsync: typeof FunctionalTry.tryAsync;