### Install @justmiracle/result Source: https://github.com/rin-yato/miracle-result/blob/main/README.md Installation instructions for the @justmiracle/result package using popular package managers like npm, yarn, pnpm, and bun. ```bash npm install @justmiracle/result yarn add @justmiracle/result pnpm add @justmiracle/result bun add @justmiracle/result ``` -------------------------------- ### Mix Namespace and Individual Imports with `result` and `isErr` - TypeScript Source: https://context7.com/rin-yato/miracle-result/llms.txt Shows how to combine namespace imports with individual function imports, such as `isErr`, from '@justmiracle/result'. This example defines a function that returns a Result and demonstrates conditional handling based on whether the result is an error. ```typescript import { result, isErr } from '@justmiracle/result'; // Assuming Result type is defined elsewhere or inferred // type Result = { ok: true; value: T } | { ok: false; error: E }; function processData(input: string): Result { if (!input) return result.err('Empty input'); return result.ok(input.length); } const output = processData('test'); if (isErr(output)) { console.error('Failed:', output.error); } else { console.log('Length:', output.value); } ``` -------------------------------- ### Checking Result Type with isOk and isErr (TypeScript) Source: https://github.com/rin-yato/miracle-result/blob/main/README.md Provides examples of using `isOk` and `isErr` functions to determine if a Result is a success or an error, allowing for conditional handling of the value or error. ```typescript if (isOk(successResult)) { console.log('Success:', successResult.value); } else { console.error('Error:', successResult.error); } if (isErr(errorResult)) { console.error('Error:', errorResult.error); } else { console.log('Success:', errorResult.value); } ``` -------------------------------- ### Default Export Usage for Results with `result.err` and `result.ok` - TypeScript Source: https://context7.com/rin-yato/miracle-result/llms.txt Demonstrates using the default export of the '@justmiracle/result' library. This example defines a safe division function that returns a Result type and showcases unwrapping the result with a default value using `unwrapOr`. ```typescript import result from '@justmiracle/result'; // Assuming Result type is defined elsewhere or inferred // type Result = { ok: true; value: T } | { ok: false; error: E }; const safeDiv = (a: number, b: number): Result => { if (b === 0) return result.err('Division by zero'); return result.ok(a / b); }; const divResult = safeDiv(10, 2); console.log(result.unwrapOr(divResult, -1)); // 5 ``` -------------------------------- ### Convert Throwing Functions to Result Type with TypeScript Source: https://context7.com/rin-yato/miracle-result/llms.txt Shows how to use `makeSafe` to wrap functions that might throw exceptions into new functions that return a Result type. This allows for safer error handling, especially with built-in functions like `JSON.parse` or custom risky operations. Includes practical examples for file operations and chaining safe operations. ```typescript import { makeSafe, isOk, isErr, Result } from '@justmiracle/result'; // Wrap JSON.parse which throws on invalid input const safeJsonParse = makeSafe(JSON.parse); const validResult = safeJsonParse('{"name": "Alice", "age": 30}'); if (isOk(validResult)) { console.log('Parsed:', validResult.value); // { name: 'Alice', age: 30 } } else { console.error('Parse error:', validResult.error); } const invalidResult = safeJsonParse('{ invalid json }'); if (isErr(invalidResult)) { console.error('Parse failed:', invalidResult.error); // SyntaxError: ... } // Wrap custom unsafe functions function riskyOperation(value: string): number { if (value === '') throw new Error('Empty string not allowed'); return parseInt(value, 10); } const safeRiskyOp = makeSafe(riskyOperation); const result1 = safeRiskyOp('123'); console.log(result1); // { value: 123, error: null } const result2 = safeRiskyOp(''); console.log(result2); // { value: null, error: Error: Empty string not allowed } // Practical example: File operations import { readFileSync } from 'fs'; const safeReadFile = makeSafe(readFileSync); const fileResult = safeReadFile('config.json', 'utf-8'); if (isOk(fileResult)) { const configResult = safeJsonParse(fileResult.value); if (isOk(configResult)) { console.log('Config loaded:', configResult.value); } else { console.error('Invalid JSON in config file'); } } else { console.error('Failed to read config file:', fileResult.error); } // Chain multiple safe operations const safeParseInt = makeSafe(parseInt); const numberResult = safeParseInt('42', 10); console.log(numberResult); // { value: 42, error: null } ``` -------------------------------- ### Unwrapping Result Values with unwrapOr() in TypeScript Source: https://context7.com/rin-yato/miracle-result/llms.txt Explains how to use the `unwrapOr()` function to safely extract a value from a Result type, providing a default value if the Result is an error. This is demonstrated with both successful and error Result objects, a practical configuration loading example, and a scenario involving an array of Results. ```typescript import { ok, err, unwrapOr, Result } from '@justmiracle/result'; // With successful result const successResult: Result = ok(42); const value1 = unwrapOr(successResult, 0); console.log(value1); // 42 // With error result const errorResult: Result = err('Failed to load'); const value2 = unwrapOr(errorResult, 0); console.log(value2); // 0 (default value) // Practical example: Configuration loading function loadConfig(): Result<{ port: number; host: string }, Error> { try { return ok({ port: 3000, host: 'localhost' }); } catch (e) { return err(e as Error); } } const config = unwrapOr(loadConfig(), { port: 8080, host: '0.0.0.0' }); console.log(`Server starting on ${config.host}:${config.port}`); // If loadConfig fails, uses default: "Server starting on 0.0.0.0:8080" // With type inference const numbers: Result[] = [ok(1), err('error'), ok(3)]; const values = numbers.map(r => unwrapOr(r, -1)); console.log(values); // [1, -1, 3] ``` -------------------------------- ### Unwrap Values from Result Type with TypeScript Source: https://context7.com/rin-yato/miracle-result/llms.txt Demonstrates how to use the `unwrap` function to extract the successful value from a Result type or throw an error if the Result is a failure. It covers handling both primitive errors and Error objects, and provides practical examples for critical operations and pipelines. ```typescript import { ok, err, unwrap, Result } from '@justmiracle/result'; // With successful result const successResult: Result = ok(42); const value = unwrap(successResult); console.log(value); // 42 // With error result - throws the error const errorResult: Result = err('Something went wrong'); try { const value = unwrap(errorResult); } catch (e) { console.error('Caught:', e); // "Something went wrong" } // With Error object - throws the Error const errorWithObj: Result = err(new Error('Network timeout')); try { unwrap(errorWithObj); } catch (e) { console.error('Error message:', (e as Error).message); // "Network timeout" } // Practical example: Critical operations function parseConfig(json: string): Result { try { return ok(JSON.parse(json)); } catch (e) { return err(new Error('Invalid config JSON')); } } // Use unwrap when the error should crash the program const configResult = parseConfig('{"port": 3000}'); const config = unwrap(configResult); // Throws if parsing failed console.log('Starting server with config:', config); // Pipeline with unwrap const result = ok(10); const doubled = unwrap(result) * 2; console.log(doubled); // 20 ``` -------------------------------- ### Import and Use Namespace `result` for Results - TypeScript Source: https://context7.com/rin-yato/miracle-result/llms.txt Demonstrates importing the `result` namespace from '@justmiracle/result' to create and manipulate Result objects. Shows how to use helper functions like `isOk` and `unwrapOr` for explicit error management. ```typescript import { result } from '@justmiracle/result'; // Create results with namespace const success = result.ok(100); const failure = result.err('Operation failed'); // Use helper functions if (result.isOk(success)) { console.log('Value:', success.value); } const value = result.unwrapOr(failure, 0); console.log(value); // 0 ``` -------------------------------- ### Creating Results with ok() and err() Source: https://context7.com/rin-yato/miracle-result/llms.txt Demonstrates how to create successful ('Ok') and failed ('Err') result objects using the `ok()` and `err()` functions provided by the library. ```APIDOC ## Creating Results with `ok()` and `err()` ### Description Create successful or failed result objects that explicitly represent the outcome of an operation. ### Method N/A (Function calls) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { ok, err, Result } from '@justmiracle/result'; // Create a successful result const successResult: Result = ok(42); console.log(successResult); // { value: 42, error: null } // Create an error result with a string const errorResult: Result = err('Database connection failed'); console.log(errorResult); // { value: null, error: 'Database connection failed' } // Create an error result with an Error object const errorWithObject: Result = err(new Error('User not found')); console.log(errorWithObject); // { value: null, error: Error: User not found } // Use in a function function divide(a: number, b: number): Result { if (b === 0) return err('Division by zero'); return ok(a / b); } const result1 = divide(10, 2); // { value: 5, error: null } const result2 = divide(10, 0); // { value: null, error: 'Division by zero' } ``` ### Response #### Success Response (N/A) N/A #### Response Example ```json { "value": 42, "error": null } // or { "value": null, "error": "Database connection failed" } ``` ``` -------------------------------- ### Creating Results with ok() and err() in TypeScript Source: https://context7.com/rin-yato/miracle-result/llms.txt Demonstrates how to create successful (Ok) and failed (Err) result objects using the `ok()` and `err()` functions from the `@justmirmiracle/result` library. It shows how to represent different types of values and errors, and how to use these results within functions for explicit error handling. ```typescript import { ok, err, Result } from '@justmiracle/result'; // Create a successful result const successResult: Result = ok(42); console.log(successResult); // { value: 42, error: null } // Create an error result with a string const errorResult: Result = err('Database connection failed'); console.log(errorResult); // { value: null, error: 'Database connection failed' } // Create an error result with an Error object const errorWithObject: Result = err(new Error('User not found')); console.log(errorWithObject); // { value: null, error: Error: User not found } // Use in a function function divide(a: number, b: number): Result { if (b === 0) return err('Division by zero'); return ok(a / b); } const result1 = divide(10, 2); // { value: 5, error: null } const result2 = divide(10, 0); // { value: null, error: 'Division by zero' } ``` -------------------------------- ### Import and Use Alias `r` for Results - TypeScript Source: https://context7.com/rin-yato/miracle-result/llms.txt Illustrates using the shorter alias `r` for the '@justmiracle/result' namespace. This provides a more concise way to create and unwrap Result objects, suitable for scenarios where brevity is desired. ```typescript import { r } from '@justmiracle/result'; const data = r.ok({ id: 1, name: 'Product' }); const extracted = r.unwrap(data); console.log(extracted); // { id: 1, name: 'Product' } ``` -------------------------------- ### Creating Results with ok and err Functions (TypeScript) Source: https://github.com/rin-yato/miracle-result/blob/main/README.md Demonstrates how to create success (Ok) and error (Err) results using the `ok` and `err` factory functions. Shows type inference for different error types. ```typescript import { ok, err, Result } from '@justmiracle/result'; const successResult: Result = ok(42); // { value: 42, error: null } const errorResult: Result = err('Something went wrong'); // { value: null, error: 'Something went wrong' } const errorResult2: Result = err(new Error('Another error')); // { value: null, error: Error } ``` -------------------------------- ### Checking Result State with isOk() and isErr() in TypeScript Source: https://context7.com/rin-yato/miracle-result/llms.txt Illustrates the use of `isOk()` and `isErr()` utility functions for type-safe checking of Result states in TypeScript. These guards help narrow down the Result type, allowing TypeScript to infer the correct `value` or `error` property safely. It also shows an alternative direct property checking method. ```typescript import { ok, err, isOk, isErr, Result } from '@justmiracle/result'; function fetchUser(id: number): Result<{ name: string; age: number }, string> { if (id === 1) return ok({ name: 'Alice', age: 30 }); return err('User not found'); } const userResult = fetchUser(1); // Using isOk if (isOk(userResult)) { // TypeScript knows userResult.value is { name: string; age: number } console.log('Success:', userResult.value.name, userResult.value.age); // userResult.error is null here } else { // TypeScript knows userResult.error is string console.error('Error:', userResult.error); // userResult.value is null here } // Using isErr if (isErr(userResult)) { console.error('Failed:', userResult.error); return; } // After the check, TypeScript knows it's Ok console.log('User:', userResult.value); // Direct property checking (alternative) const result = fetchUser(2); if (result.error) { console.error('Error occurred:', result.error); return result; } console.log('Got user:', result.value); ``` -------------------------------- ### Unwrapping Result with unwrapOr (TypeScript) Source: https://github.com/rin-yato/miracle-result/blob/main/README.md Demonstrates the `unwrapOr` function, which safely extracts the value from a `Result`. It returns the contained value if it's `Ok`, otherwise returns a provided default value. ```typescript const resultOne = ok(42); const value = unwrapOr(resultOne, 12); // 42 const resultTwo = err('Something went wrong'); const value2 = unwrapOr(resultTwo, 12); // 12 (default value) ``` -------------------------------- ### Checking Result State with isOk() and isErr() Source: https://context7.com/rin-yato/miracle-result/llms.txt Provides type-safe guard functions `isOk()` and `isErr()` to check the state of a Result object and narrow down its type for safer access to `value` or `error` properties. ```APIDOC ## Checking Result State with `isOk()` and `isErr()` ### Description Type-safe guard functions that narrow the Result type and enable TypeScript to infer the correct properties. ### Method N/A (Function calls) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { ok, err, isOk, isErr, Result } from '@justmiracle/result'; function fetchUser(id: number): Result<{ name: string; age: number }, string> { if (id === 1) return ok({ name: 'Alice', age: 30 }); return err('User not found'); } const userResult = fetchUser(1); // Using isOk if (isOk(userResult)) { // TypeScript knows userResult.value is { name: string; age: number } console.log('Success:', userResult.value.name, userResult.value.age); // userResult.error is null here } else { // TypeScript knows userResult.error is string console.error('Error:', userResult.error); // userResult.value is null here } // Using isErr if (isErr(userResult)) { console.error('Failed:', userResult.error); return; } // After the check, TypeScript knows it's Ok console.log('User:', userResult.value); // Direct property checking (alternative) const result = fetchUser(2); if (result.error) { console.error('Error occurred:', result.error); return result; } console.log('Got user:', result.value); ``` ### Response #### Success Response (N/A) N/A #### Response Example ```json // When isOk is true: { "value": { "name": "Alice", "age": 30 }, "error": null } // When isErr is true: { "value": null, "error": "User not found" } ``` ``` -------------------------------- ### Result Type Definitions: Result, Ok, Err in TypeScript Source: https://context7.com/rin-yato/miracle-result/llms.txt Defines the core types `Result`, `Ok`, and `Err` which represent the success or failure states of an operation. Illustrates their usage with generic types, custom error classes, union types for errors, and explicit return type annotations. ```typescript import { Result, Ok, Err, ok, err } from '@justmiracle/result'; // Result is a union of Ok and Err type MyResult = Result; // Equivalent to: Ok | Err // Ok type structure const success: Ok = { value: 'Hello', error: null }; // Err type structure const failure: Err = { value: null, error: 'Failed' }; // Using with custom error types class ValidationError { constructor(public field: string, public message: string) {} } function validateEmail(email: string): Result { if (!email.includes('@')) { return err(new ValidationError('email', 'Must contain @')); } return ok(email); } const emailResult = validateEmail('invalid'); if (emailResult.error) { console.log(`${emailResult.error.field}: ${emailResult.error.message}`); // Output: "email: Must contain @" } // Multiple error types with union type FetchError = 'NetworkError' | 'TimeoutError' | 'NotFoundError'; function fetchData(url: string): Result<{ data: string }, FetchError> { if (!url) return err('NotFoundError'); return ok({ data: 'response data' }); } const data = fetchData(''); if (data.error === 'NotFoundError') { console.log('Resource not found'); } // Explicit return type annotation for error union function complexOperation(): Result { if (Math.random() > 0.5) return err('ErrorA'); if (Math.random() > 0.3) return ok(42); return err('ErrorB'); } // Without annotation, TypeScript infers: Ok<42> | Err<"ErrorA"> | Err<"ErrorB"> ``` -------------------------------- ### Unwrapping Result with unwrap (TypeScript) Source: https://github.com/rin-yato/miracle-result/blob/main/README.md Explains the `unwrap` function, which attempts to extract the value from a `Result`. It returns the value if `Ok`, but throws an error if the `Result` is `Err`, requiring careful handling. ```typescript const resultOne = ok(42); const value = unwrap(resultOne); // 42 const resultTwo = err('Something went wrong'); const value2 = unwrap(resultTwo); // throws 'Something went wrong' ``` -------------------------------- ### Result Type Definitions in TypeScript Source: https://github.com/rin-yato/miracle-result/blob/main/README.md Defines the core Result, Ok, and Err types in TypeScript. Result is a discriminated union, Ok holds a value and null error, while Err holds null value and an error. ```typescript // A result is either successful or an error export type Result = Ok | Err; // A successful result contains a value and null for error export type Ok = { value: T; error: null }; // An error result contains null for value and an error export type Err = { value: null; error: E }; ``` -------------------------------- ### Direct Result Type Checking (TypeScript) Source: https://github.com/rin-yato/miracle-result/blob/main/README.md Illustrates how to check for the presence of an error or a value directly on the result object, offering an alternative to `isOk` and `isErr` functions. ```typescript const result = someFunctionReturningResult(); if (result.error) { // Handle error console.error('Error:', result.error); return result; } // Otherwise, handle success console.log('Success:', result.value); const result = someFunctionReturningResult(); if (result.value !== null) { // Handle success console.log('Success:', result.value); } else { // Handle error console.error('Error:', result.error); } ``` -------------------------------- ### TypeScript Error Type Inference Limitation and Best Practice Source: https://github.com/rin-yato/miracle-result/blob/main/README.md Illustrates a TypeScript limitation where multiple `err` calls result in separate `Err` types instead of a union. Shows the best practice of explicit return type annotation to achieve the desired union error type. ```typescript function test(): Ok<42> | Err<"A" | "B"> { if (something) return err("A"); if (other) return ok(42); return err("B"); } function test() { if (something) return err("A"); if (other) return ok(42); return err("B"); } // Inferred: Ok<42> | Err<"A"> | Err<"B"> ``` -------------------------------- ### Unwrapping Values with unwrapOr() Source: https://context7.com/rin-yato/miracle-result/llms.txt Safely extracts the `value` from a Result object. If the Result is an `Err`, it returns a provided default value instead. ```APIDOC ## Unwrapping Values with `unwrapOr()` ### Description Extract the value from a Result, providing a default value if the Result is an error. ### Method N/A (Function calls) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { ok, err, unwrapOr, Result } from '@justmiracle/result'; // With successful result const successResult: Result = ok(42); const value1 = unwrapOr(successResult, 0); console.log(value1); // 42 // With error result const errorResult: Result = err('Failed to load'); const value2 = unwrapOr(errorResult, 0); console.log(value2); // 0 (default value) // Practical example: Configuration loading function loadConfig(): Result<{ port: number; host: string }, Error> { try { // Simulate successful config loading return ok({ port: 3000, host: 'localhost' }); } catch (e) { return err(e as Error); } } const config = unwrapOr(loadConfig(), { port: 8080, host: '0.0.0.0' }); console.log(`Server starting on ${config.host}:${config.port}`); // If loadConfig fails, uses default: "Server starting on 0.0.0.0:8080" // With type inference const numbers: Result[] = [ok(1), err('error'), ok(3)]; const values = numbers.map(r => unwrapOr(r, -1)); console.log(values); // [1, -1, 3] ``` ### Response #### Success Response (N/A) N/A #### Response Example ```json // For ok(42) with default 0: 42 // For err('Failed to load') with default 0: 0 // For successful loadConfig with default { port: 8080, host: '0.0.0.0' }: { "port": 3000, "host": "localhost" } // For failed loadConfig with default { port: 8080, host: '0.0.0.0' }: { "port": 8080, "host": "0.0.0.0" } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.