Skip to content

Instantly share code, notes, and snippets.

@mimshins
Last active March 20, 2025 09:14
Show Gist options
  • Select an option

  • Save mimshins/730f187b0d273ab0b2d211385041063c to your computer and use it in GitHub Desktop.

Select an option

Save mimshins/730f187b0d273ab0b2d211385041063c to your computer and use it in GitHub Desktop.
An utility function to help resolve throwables in a declarative way.
type Success<T> = {
data: T;
error: null;
};
type Failure<E> = {
data: null;
error: E;
};
type Result<T, E extends Error = Error> = Promise<Success<T> | Failure<E>>;
export const resolveThrowable = async <
E extends Error,
F extends (...args: any[]) => any,
>(
throwableFn: F,
): Result<Awaited<ReturnType<F>>, E> => {
type T = Awaited<ReturnType<F>>;
try {
const data = (await throwableFn()) as T;
return { data, error: null };
} catch (err) {
return { data: null, error: err as E };
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment