UNPKG

wellcrafted

Version:

Delightful TypeScript patterns for elegant, type-safe applications

364 lines (363 loc) 14.3 kB
//#region src/result/result.ts /** * Constructs an `Ok<T>` variant, representing a successful outcome. * * This factory function creates the success variant of a `Result`. * It wraps the provided `data` (the success value) and ensures the `error` property is `null`. * * @template T - The type of the success value. * @param data - The success value to be wrapped in the `Ok` variant. * @returns An `Ok<T>` object with the provided data and `error` set to `null`. * @example * ```ts * const successfulResult = Ok("Operation completed successfully"); * // successfulResult is { data: "Operation completed successfully", error: null } * ``` */ const Ok = (data) => ({ data, error: null }); /** * Constructs an `Err<E>` variant, representing a failure outcome. * * Wraps the provided `error` (the failure value) and sets `data` to `null`. * * **Don't call `Err(null)`.** It produces `{ data: null, error: null }`, * structurally identical to `Ok(null)`. The built-in `isErr` check * (`result.error !== null`) reads it as Ok, silently misclassifying your * failure as success. `Err(undefined)` is also discouraged: the discriminator * technically works (`undefined !== null`), but `undefined` is falsy, so * downstream `if (error)` checks trip and the error carries no information * anyway. Pass a meaningful error value (a string, a tagged error from * `defineErrors`, an `Error` instance), or use `Ok(null)`/`Ok(undefined)` if * what you meant was success-with-no-payload. * * At `catch (error: unknown)` boundaries, wrap the caught value in a tagged * error rather than passing it through. A `defineErrors` factory like * `MyError.Unexpected({ cause: error })` is always non-null by construction, * so the discriminator works regardless of what was thrown. * * See `docs/philosophy/err-null-is-ok-null.md` for the full rationale. * * @template E - The type of the error value. * @param error - The error value to wrap. Don't pass `null` or `undefined`. * @returns An `Err<E>` object with the provided error and `data` set to `null`. * @example * ```ts * const failedResult = Err(new TypeError("Invalid input")); * // failedResult is { error: TypeError("Invalid input"), data: null } * ``` */ const Err = (error) => ({ error, data: null }); /** * Type guard to runtime check if an unknown value is a valid `Result<T, E>`. * * A value is considered a valid `Result` if: * 1. It is a non-null object. * 2. It has both `data` and `error` properties. * * The `error` property is the runtime discriminant: * - `error === null` represents `Ok<T>`, even when `data` is also `null` (`Ok(null)`). * - `error !== null` represents `Err<E>`, even if external data also includes a non-null `data` value. * * This function checks only the Result shape. It does not validate the * success or error payload types. * * @template T - The expected type of the success value if the value is an `Ok` variant (defaults to `unknown`). * @template E - The expected type of the error value if the value is an `Err` variant (defaults to `unknown`). * @param value - The value to check. * @returns `true` if the value conforms to the `Result` structure, `false` otherwise. * If `true`, TypeScript's type system will narrow `value` to `Result<T, E>`. * @example * ```ts * declare const someValue: unknown; * * if (isResult<string, Error>(someValue)) { * // someValue is now typed as Result<string, Error> * if (isOk(someValue)) { * console.log(someValue.data); // string * } else { * console.error(someValue.error); // Error * } * } * ``` */ function isResult(value) { const isNonNullObject = typeof value === "object" && value !== null; if (!isNonNullObject) return false; const hasDataProperty = "data" in value; const hasErrorProperty = "error" in value; if (!hasDataProperty || !hasErrorProperty) return false; return true; } /** * Type guard to runtime check if a `Result<T, E>` is an `Ok<T>` variant. * * This function narrows the type of a `Result` to `Ok<T>` if it represents a successful outcome. * An `Ok<T>` variant is identified by its `error` property being `null`. * * @template T - The success value type. * @template E - The error value type. * @param result - The `Result<T, E>` to check. * @returns `true` if the `result` is an `Ok<T>` variant, `false` otherwise. * If `true`, TypeScript's type system will narrow `result` to `Ok<T>`. * @example * ```ts * declare const myResult: Result<number, string>; * * if (isOk(myResult)) { * // myResult is now typed as Ok<number> * console.log("Success value:", myResult.data); // myResult.data is number * } * ``` */ function isOk(result) { return result.error === null; } /** * Type guard to runtime check if a `Result<T, E>` is an `Err<E>` variant. * * This function narrows the type of a `Result` to `Err<E>` if it represents a failure outcome. * An `Err<E>` variant is identified by its `error` property being non-`null`. * The error side is the reliable discriminator because `Ok(null)` is valid. * * @template T - The success value type. * @template E - The error value type. * @param result - The `Result<T, E>` to check. * @returns `true` if the `result` is an `Err<E>` variant, `false` otherwise. * If `true`, TypeScript's type system will narrow `result` to `Err<E>`. * @example * ```ts * declare const myResult: Result<number, string>; * * if (isErr(myResult)) { * // myResult is now typed as Err<string> * console.error("Error value:", myResult.error); // myResult.error is string * } * ``` */ function isErr(result) { return result.error !== null; } /** * Executes a synchronous operation and wraps its outcome in a Result type. * * This function attempts to execute the `try` operation: * - If the `try` operation completes successfully, its return value is wrapped in an `Ok<T>` variant. * - If the `try` operation throws an exception, the caught exception (of type `unknown`) is passed to * the `catch` function, which transforms it into either an `Ok<T>` (recovery) or `Err<E>` (propagation). * * The return type is automatically determined by what your catch function returns: * - If catch always returns `Ok<T>`, the return type collapses to `Ok<T>` (guaranteed success) * - If catch always returns `Err<E>`, the return type is `Ok<T> | Err<E>` (may succeed or fail) * - If catch returns a union like `Err<A> | Err<B>`, the return type is `Ok<T> | Err<A> | Err<B>` (union propagation) * - If catch can return either `Ok<T>` or `Err<E>`, the return type is `Ok<T> | Err<E>` (conditional recovery) * * @template T - The success value type * @template R - The return type of the catch handler (`Ok<T>` for recovery, `Err<E>` for propagation, or a union) * @param options - Configuration object * @param options.try - The operation to execute * @param options.catch - Error handler that transforms caught exceptions into either `Ok<T>` (recovery) or `Err<E>` (propagation) * @returns `Ok<T> | R` — the union of the success path and whatever the catch handler returns * * @example * ```ts * // Returns Ok<string> - guaranteed success since catch always returns Ok * const alwaysOk = trySync({ * try: () => JSON.parse(input), * catch: () => Ok("fallback") // Always Ok<T> * }); * * // Returns Result<object, string> - may fail since catch always returns Err * const mayFail = trySync({ * try: () => JSON.parse(input), * catch: (err) => Err("Parse failed") // Returns Err<E> * }); * * // Returns Result<void, MyError> - conditional recovery based on error type * const conditional = trySync({ * try: () => riskyOperation(), * catch: (err) => { * if (isRecoverable(err)) return Ok(undefined); * return MyErr({ message: "Unrecoverable" }); * } * }); * ``` */ function trySync({ try: operation, catch: catchFn }) { try { const data = operation(); return Ok(data); } catch (error) { return catchFn(error); } } /** * Executes an asynchronous operation and wraps its outcome in a Promise<Result>. * * This function attempts to execute the `try` operation: * - If the `try` operation resolves successfully, its resolved value is wrapped in an `Ok<T>` variant. * - If the `try` operation rejects or throws an exception, the caught error (of type `unknown`) is passed to * the `catch` function, which transforms it into either an `Ok<T>` (recovery) or `Err<E>` (propagation). * * The return type is automatically determined by what your catch function returns: * - If catch always returns `Ok<T>`, the return type collapses to `Promise<Ok<T>>` (guaranteed success) * - If catch always returns `Err<E>`, the return type is `Promise<Ok<T> | Err<E>>` (may succeed or fail) * - If catch returns a union like `Err<A> | Err<B>`, the return type is `Promise<Ok<T> | Err<A> | Err<B>>` (union propagation) * - If catch can return either `Ok<T>` or `Err<E>`, the return type is `Promise<Ok<T> | Err<E>>` (conditional recovery) * * @template T - The success value type * @template R - The return type of the catch handler (`Ok<T>` for recovery, `Err<E>` for propagation, or a union) * @param options - Configuration object * @param options.try - The async operation to execute * @param options.catch - Error handler that transforms caught exceptions/rejections into either `Ok<T>` (recovery) or `Err<E>` (propagation) * @returns `Promise<Ok<T> | R>` — the union of the success path and whatever the catch handler returns * * @example * ```ts * // Returns Promise<Ok<Response>> - guaranteed success since catch always returns Ok * const alwaysOk = tryAsync({ * try: async () => fetch(url), * catch: () => Ok(new Response()) // Always Ok<T> * }); * * // Returns Promise<Result<Response, Error>> - may fail since catch always returns Err * const mayFail = tryAsync({ * try: async () => fetch(url), * catch: (err) => Err(new Error("Fetch failed")) // Returns Err<E> * }); * * // Returns Promise<Result<void, BlobError>> - conditional recovery based on error type * const conditional = await tryAsync({ * try: async () => { * await deleteFile(filename); * }, * catch: (err) => { * if ((err as { name?: string }).name === 'NotFoundError') { * return Ok(undefined); // Already deleted, that's fine * } * return BlobErr({ message: "Delete failed" }); * } * }); * ``` */ async function tryAsync({ try: operation, catch: catchFn }) { try { const data = await operation(); return Ok(data); } catch (error) { return catchFn(error); } } /** * Resolves a value that may or may not be wrapped in a `Result`, returning the final value. * * This function handles the common pattern where a value might be a `Result<T, E>` or a plain `T`: * - If `value` is an `Ok<T>` variant, returns the contained success value. * - If `value` is an `Err<E>` variant, throws the contained error value. * - If `value` is not a `Result` (i.e., it's already a plain value of type `T`), * returns it as-is. * * This is useful when working with APIs that might return either direct values or Results, * allowing you to normalize them to the actual value or propagate errors via throwing. * * Use `resolve` when the input might or might not be a Result. * Use `unwrap` when you know the input is definitely a Result. * * @template T - The type of the success value (if `value` is `Ok<T>`) or the type of the plain value. * @template E - The type of the error value (if `value` is `Err<E>`). * @param value - The value to resolve. Can be a `Result<T, E>` or a plain value of type `T`. * @returns The final value of type `T` if `value` is `Ok<T>` or if `value` is already a plain `T`. * @throws The error value `E` if `value` is an `Err<E>` variant. * * @example * ```ts * // Example with an Ok variant * const okResult = Ok("success data"); * const resolved = resolve(okResult); // "success data" * * // Example with an Err variant * const errResult = Err(new Error("failure")); * try { * resolve(errResult); * } catch (e) { * console.error(e.message); // "failure" * } * * // Example with a plain value * const plainValue = "plain data"; * const resolved = resolve(plainValue); // "plain data" * * // Example with a function that might return Result or plain value * declare function mightReturnResult(): string | Result<string, Error>; * const outcome = mightReturnResult(); * try { * const finalValue = resolve(outcome); // handles both cases * console.log("Final value:", finalValue); * } catch (e) { * console.error("Operation failed:", e); * } * ``` */ /** * Unwraps a `Result<T, E>`, returning the success value or throwing the error. * * This function extracts the data from a `Result`: * - If the `Result` is an `Ok<T>` variant, returns the contained success value of type `T`. * - If the `Result` is an `Err<E>` variant, throws the contained error value of type `E`. * * Unlike `resolve`, this function expects the input to always be a `Result` type, * making it more direct for cases where you know you're working with a `Result`. * * @template T - The type of the success value contained in the `Ok<T>` variant. * @template E - The type of the error value contained in the `Err<E>` variant. * @param result - The `Result<T, E>` to unwrap. * @returns The success value of type `T` if the `Result` is `Ok<T>`. * @throws The error value of type `E` if the `Result` is `Err<E>`. * * @example * ```ts * // Example with an Ok variant * const okResult = Ok("success data"); * const value = unwrap(okResult); // "success data" * * // Example with an Err variant * const errResult = Err(new Error("something went wrong")); * try { * unwrap(errResult); * } catch (error) { * console.error(error.message); // "something went wrong" * } * * // Usage in a function that returns Result * function divide(a: number, b: number): Result<number, string> { * if (b === 0) return Err("Division by zero"); * return Ok(a / b); * } * * try { * const result = unwrap(divide(10, 2)); // 5 * console.log("Result:", result); * } catch (error) { * console.error("Division failed:", error); * } * ``` */ function unwrap(result) { if (isOk(result)) return result.data; throw result.error; } function resolve(value) { if (isResult(value)) { if (isOk(value)) return value.data; throw value.error; } return value; } //#endregion export { Err, Ok, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap }; //# sourceMappingURL=result-C_ph_izC.js.map