UNPKG

@voiys/tagged-result

Version:

A TypeScript utility for creating tagged result unions (success/error).

61 lines 1.72 kB
"use strict"; // --- Internal Type Definitions --- Object.defineProperty(exports, "__esModule", { value: true }); exports.Result = void 0; // Implementation of 'ok' function ok(...args) { if (args.length === 1) { // Corresponds to: ok<D>(data: D) return { type: "SUCCESS", data: args[0], }; } // Corresponds to: ok<T extends Uppercase<string>, D>(type: T, data: D) // The type is already uppercase, just add SUCCESS_ prefix const prefixedType = `SUCCESS_${args[0]}`; return { type: prefixedType, data: args[1], }; } // Implementation of 'err' function err(...args) { if (args.length === 1) { // Corresponds to: err<D>(data: D) return { type: "ERROR", data: args[0], }; } // Corresponds to: err<T extends Uppercase<string>, D>(type: T, data: D) // The type is already uppercase, just add ERROR_ prefix const prefixedType = `ERROR_${args[0]}`; return { type: prefixedType, data: args[1], }; } /** * A utility object containing helper functions to create `ResultType` objects * for representing operation outcomes (success or error). * * @example * ```typescript * import { Result, ResultType } from 'tagged-result'; * * function process(): ResultType<"SUCCESS_PROCESSED", string> | ResultType<"ERROR_FAILED", Error> { * try { * const data = someOperation(); * return Result.ok("PROCESSED", data); // becomes "SUCCESS_PROCESSED" * } catch (e) { * return Result.err("FAILED", e as Error); // becomes "ERROR_FAILED" * } * } * ``` */ exports.Result = { ok, err, }; //# sourceMappingURL=index.js.map