/** * Represents a successful result. * @template T The type of the value. */ export class Ok { readonly value: T; constructor(value: T) { this.value = value; } /** * Type guard to check if this result is an `Ok` result. * @returns {this is Ok} `true` if the result is an `Ok` result, otherwise `false`. */ isOk(): this is Ok { return true; } /** * Type guard to check if this result is an `Err` result. * @returns {this is Err} `true` if the result is an `Err` result, otherwise `false`. */ isErr(): this is Err { return false; } } /** * Represents a failed result. * @template E The type of the error. */ export class Err { readonly error: E; constructor(error: E) { this.error = error; } /** * Type guard to check if this result is an `Ok` result. * @returns {this is Ok} `true` if the result is an `Ok` result, otherwise `false`. */ isOk(): this is Ok { return false; } /** * Type guard to check if this result is an `Err` result. * @returns {this is Err} `true` if the result is an `Err` result, otherwise `false`. */ isErr(): this is Err { return true; } } /** * A union type that represents either a successful result (`Ok`) or a failed result (`Err`). * @template T The type of the value in the `Ok` case. * @template E The type of the error in the `Err` case. */ export type Result = Ok | Err; /** * Creates a successful result. * @template T The type of the value. * @param {T} value The value to wrap in an `Ok` result. * @returns {Ok} The `Ok` result containing the value. */ export function OkResult(value: T): Ok { return new Ok(value); } /** * Creates a failed result. * @template E The type of the error. * @param {E} error The error to wrap in an `Err` result. * @returns {Err} The `Err` result containing the error. */ export function ErrResult(error: E): Err { return new Err(error); } /** * Wraps a synchronous function in a try-catch block, returning a `Result`. * @template T The type of the value returned by the function. * @param {() => T} fn The function to execute. * @returns {Result} An `Ok` result if the function succeeds, or an `Err` result if it throws an error. */ export function withResult(fn: () => T): Result { try { return new Ok(fn()); } catch (error) { return new Err(error instanceof Error ? error : new Error(String(error))); } } /** * Wraps an asynchronous function in a try-catch block, returning a `Promise` of a `Result`. * @template T The type of the value returned by the function. * @param {() => Promise} fn The asynchronous function to execute. * @returns {Promise>} A `Promise` resolving to an `Ok` result if the function succeeds, or an `Err` result if it throws an error. */ export async function withResultAsync(fn: () => Promise): Promise> { try { const result = await fn(); return new Ok(result); } catch (error) { return new Err(error instanceof Error ? error : new Error(String(error))); } }