Created
January 6, 2026 09:06
-
-
Save nandordudas/10ec503a613b6c6aed42e95df429563c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| interface Success<T> { | |
| data: T | |
| success: true | |
| } | |
| interface Failure<E extends Error = Error> { | |
| error: E | |
| success: false | |
| } | |
| export type Result<T, E extends Error = Error> = | |
| | Success<T> | |
| | Failure<E> | |
| function success<T>(data: T): Success<T> { | |
| return { | |
| data, | |
| success: true, | |
| } | |
| } | |
| function failure<E extends Error = Error>(error: E): Failure<E> { | |
| return { | |
| error, | |
| success: false, | |
| } | |
| } | |
| function transformError(value: unknown): Error { | |
| if (value instanceof Error) | |
| return value | |
| return new Error(String(value)) | |
| } | |
| async function tryResolve<T, E extends Error = Error>( | |
| value: T | Promise<T> | |
| ): Promise<Result<Awaited<T>, E>> { | |
| try { | |
| const data = await Promise.resolve(value) | |
| return success(data) | |
| } | |
| catch (error) { | |
| return failure(transformError(error) as E) | |
| } | |
| } | |
| async function tryCall<T, E extends Error = Error>( | |
| fn: () => T | Promise<T> | |
| ): Promise<Result<Awaited<T>, E>> { | |
| try { | |
| const data = await Promise.resolve(fn()) | |
| return success(data) | |
| } | |
| catch (error) { | |
| return failure(transformError(error) as E) | |
| } | |
| } | |
| export async function attempt<T, E extends Error = Error>( | |
| value: T | Promise<T> | (() => T | Promise<T>) | |
| ): Promise<Result<Awaited<T>, E>> { | |
| return typeof value === 'function' | |
| ? tryCall(value as () => T | Promise<T>) | |
| : tryResolve(value) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment