wellcrafted
Version:
Delightful TypeScript patterns for elegant, type-safe applications
440 lines • 18.6 kB
TypeScript
//#region src/result/result.d.ts
/**
* Represents the successful outcome of an operation, encapsulating the success value.
*
* This is the 'Ok' variant of the `Result` type. It holds a `data` property
* of type `T` (the success value) and an `error` property explicitly set to `null`,
* signifying no error occurred.
*
* Use this type in conjunction with `Err<E>` and `Result<T, E>`.
*
* @template T - The type of the success value contained within.
*/
type Ok<T> = {
data: T;
error: null;
};
/**
* Represents the failure outcome of an operation, encapsulating the error value.
*
* This is the 'Err' variant of the `Result` type. It holds an `error` property
* of type `E` (the error value) and a `data` property explicitly set to `null`,
* signifying that no success value is present due to the failure.
*
* Use this type in conjunction with `Ok<T>` and `Result<T, E>`.
*
* @template E - The type of the error value contained within.
*/
type Err<E> = {
error: E;
data: null;
};
/**
* A type that represents the outcome of an operation that can either succeed or fail.
*
* `Result<T, E>` is a discriminated union type with two possible variants:
* - `Ok<T>`: Represents a successful outcome, containing a `data` field with the success value of type `T`.
* In this case, the `error` field is `null`.
* - `Err<E>`: Represents a failure outcome, containing an `error` field with the error value of type `E`.
* In this case, the `data` field is `null`.
*
* This type promotes explicit error handling by requiring developers to check
* the variant of the `Result` before accessing its potential value or error.
* It helps avoid runtime errors often associated with implicit error handling (e.g., relying on `try-catch` for all errors).
*
* @template T - The type of the success value if the operation is successful (held in `Ok<T>`).
* @template E - The type of the error value if the operation fails (held in `Err<E>`).
* @example
* ```ts
* function divide(numerator: number, denominator: number): Result<number, string> {
* if (denominator === 0) {
* return Err("Cannot divide by zero");
* }
* return Ok(numerator / denominator);
* }
*
* const result1 = divide(10, 2);
* if (isOk(result1)) {
* console.log("Success:", result1.data); // Output: Success: 5
* }
*
* const result2 = divide(10, 0);
* if (isErr(result2)) {
* console.error("Failure:", result2.error); // Output: Failure: Cannot divide by zero
* }
* ```
*/
type Result<T, E> = Ok<T> | Err<E>;
/**
* 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 }
* ```
*/
declare const Ok: <T>(data: T) => Ok<T>;
/**
* 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 }
* ```
*/
declare const Err: <E>(error: E) => Err<E>;
/**
* Utility type to extract the success value's type `T` from a `Result<T, E>` type.
*
* If `R` is an `Ok<T>` variant (or a `Result<T, E>` that could be an `Ok<T>`),
* this type resolves to `T`. If `R` can only be an `Err<E>` variant, it resolves to `never`.
* This is useful for obtaining the type of the `data` field when you know you have a success.
*
* @template R - The `Result<T, E>` type from which to extract the success value's type.
* Must extend `Result<unknown, unknown>`.
* @example
* ```ts
* type MyResult = Result<number, string>;
* type SuccessValueType = UnwrapOk<MyResult>; // SuccessValueType is number
*
* type MyErrorResult = Err<string>;
* type ErrorValueType = UnwrapOk<MyErrorResult>; // ErrorValueType is never
* ```
*/
type UnwrapOk<R extends Result<unknown, unknown>> = R extends Ok<infer U> ? U : never;
/**
* Utility type to extract the error value's type `E` from a `Result<T, E>` type.
*
* If `R` is an `Err<E>` variant (or a `Result<T, E>` that could be an `Err<E>`),
* this type resolves to `E`. If `R` can only be an `Ok<T>` variant, it resolves to `never`.
* This is useful for obtaining the type of the `error` field when you know you have a failure.
*
* @template R - The `Result<T, E>` type from which to extract the error value's type.
* Must extend `Result<unknown, unknown>`.
* @example
* ```ts
* type MyResult = Result<number, string>;
* type ErrorValueType = UnwrapErr<MyResult>; // ErrorValueType is string
*
* type MySuccessResult = Ok<number>;
* type SuccessValueType = UnwrapErr<MySuccessResult>; // SuccessValueType is never
* ```
*/
type UnwrapErr<R extends Result<unknown, unknown>> = R extends Err<infer E> ? E : never;
/**
* 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
* }
* }
* ```
*/
declare function isResult<T = unknown, E = unknown>(value: unknown): value is Result<T, E>;
/**
* 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
* }
* ```
*/
declare function isOk<T, E>(result: Result<T, E>): result is Ok<T>;
/**
* 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
* }
* ```
*/
declare function isErr<T, E>(result: Result<T, E>): result is Err<E>;
/**
* 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" });
* }
* });
* ```
*/
declare function trySync<T, R extends Ok<T> | Err<any>>({
try: operation,
catch: catchFn
}: {
try: () => T;
catch: (error: unknown) => R;
}): Ok<T> | R;
/**
* 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" });
* }
* });
* ```
*/
declare function tryAsync<T, R extends Ok<T> | Err<any>>({
try: operation,
catch: catchFn
}: {
try: () => Promise<T>;
catch: (error: unknown) => R;
}): Promise<Ok<T> | R>;
/**
* 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);
* }
* ```
*/
declare function unwrap<T, E>(result: Result<T, E>): T;
declare function resolve<T, E>(value: T | Result<T, E>): T;
//# sourceMappingURL=result.d.ts.map
//#endregion
export { Err, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap };
//# sourceMappingURL=result-_socO0Ud.d.ts.map