### Install @voiys/tagged-result package Source: https://github.com/voiys/tagged-result/blob/main/README.md Instructions for installing the @voiys/tagged-result package using various package managers like npm, yarn, pnpm, and bun. ```bash npm install @voiys/tagged-result ``` ```bash yarn add @voiys/tagged-result ``` ```bash pnpm add @voiys/tagged-result ``` ```bash bun add @voiys/tagged-result ``` -------------------------------- ### Writing Basic Vitest Tests in TypeScript Source: https://github.com/voiys/tagged-result/blob/main/TESTING.md This snippet demonstrates the fundamental structure for writing tests using Vitest in a TypeScript project. It shows how to import necessary functions like `describe`, `test`, and `expect`, define a test suite for a feature, and write an individual test case with assertions. The example uses a hypothetical `Result` type to illustrate testing object properties. ```typescript import { describe, test, expect } from 'vitest'; import { Result } from '../src/index'; describe('My Feature', () => { test('should work correctly', () => { const result = Result.ok({ message: 'success' }); expect(result.type).toBe('success'); expect(result.data.message).toBe('success'); }); }); ``` -------------------------------- ### Quick Start with Tagged Results Source: https://github.com/voiys/tagged-result/blob/main/README.md Demonstrates basic usage of `Result.ok` and `Result.err` with default and custom tags, showcasing automatic type inference and narrowing in TypeScript. ```typescript import { Result } from '@voiys/tagged-result'; // Default success/error types const success = Result.ok({ id: 123, name: "Alice" }); // Type: { type: "SUCCESS", data: { id: number, name: string } } const error = Result.err({ message: "Something went wrong" }); // Type: { type: "ERROR", data: { message: string } } // Custom tagged variants (automatically prefixed) const tagged = Result.ok("USER_CREATED", { id: 123, name: "Alice" }); // Type: { type: "SUCCESS_USER_CREATED", data: { id: number, name: string } } const failure = Result.err("VALIDATION", { field: "email" }); // Type: { type: "ERROR_VALIDATION", data: { field: string } } // TypeScript narrows automatically if (tagged.type === "SUCCESS_USER_CREATED") { console.log(tagged.data.name); // TypeScript knows this is string } ``` -------------------------------- ### Synchronous Example with Tagged Results Source: https://github.com/voiys/tagged-result/blob/main/README.md Illustrates synchronous usage of tagged results, including type inference and explicit type declarations for function return types, with examples of parsing numbers and validating user data. ```typescript import { Result, SuccessResultType, ErrorResultType } from '@voiys/tagged-result'; // Let TypeScript infer the return type function parseNumber(input: string) { const num = parseInt(input); if (isNaN(num)) { return Result.err("INVALID_NUMBER", { input }); } return Result.ok("PARSED", { value: num }); } // Or force a specific return type function validateUser(data: any): SuccessResultType<"VALID", { id: number }> | ErrorResultType<"INVALID", { error: string }> { if (!data.id || typeof data.id !== 'number') { return Result.err("INVALID", { error: "ID must be a number" }); } return Result.ok("VALID", { id: data.id }); } // Usage const result = parseNumber("42"); if (result.type === "SUCCESS_PARSED") { console.log(result.data.value); // TypeScript knows this is number } ``` -------------------------------- ### Handling Asynchronous Data Fetching with Result Types in TypeScript Source: https://github.com/voiys/tagged-result/blob/main/README.md Demonstrates how to use the `Result` type pattern for handling success and error states in asynchronous data fetching operations. It shows examples of both inferred and explicitly defined return types for functions like `fetchData` and `getUser`, and illustrates how to consume the result using a `switch` statement for exhaustive type checking and error handling. ```typescript // Let TypeScript infer the return type async function fetchData(url: string) { try { const response = await fetch(url); if (!response.ok) { return Result.err("HTTP_ERROR", { status: response.status }); } const data = await response.json(); return Result.ok(data); } catch (error) { return Result.err("NETWORK_ERROR", { message: error.message }); } } // Or force a specific return type async function getUser(id: number): Promise | ErrorResultType<"NOT_FOUND", { message: string }> | DefaultErrorResultType<{ message: string }>> { try { const response = await fetch(`/users/${id}`); if (response.status === 404) { return Result.err("NOT_FOUND", { message: "User not found" }); } if (!response.ok) { return Result.err({ message: "Failed to fetch user" }); } const user = await response.json(); return Result.ok("USER_FOUND", user); } catch (error) { return Result.err({ message: error.message }); } } // Usage const userResult = await getUser(123); switch (userResult.type) { case "SUCCESS_USER_FOUND": console.log('User:', userResult.data); // TypeScript knows this is User break; case "ERROR_NOT_FOUND": case "ERROR": console.error(userResult.data.message); break; } ``` -------------------------------- ### API Reference: Result.ok method Source: https://github.com/voiys/tagged-result/blob/main/README.md Creates a successful result with optional custom type tag following the pattern `"SUCCESS"` or `"SUCCESS_${Uppercase}"`. ```APIDOC Result.ok(data) Result.ok(type, data) ``` ```typescript // Using default "SUCCESS" type const result1 = Result.ok({ value: 42 }); // Type: DefaultSuccessResultType<{ value: number }> // Using custom type const result2 = Result.ok("DATA_LOADED", { items: [] }); // Type: SuccessResultType<"DATA_LOADED", { items: any[] }> ``` -------------------------------- ### Best Practice: Chain Asynchronous Operations Safely with Result Types in TypeScript Source: https://github.com/voiys/tagged-result/blob/main/README.md Demonstrates a pattern for chaining multiple asynchronous operations (e.g., `fetchUser` then `validateUser`) while safely propagating errors. If an early step fails, the error is returned immediately, ensuring that subsequent operations only proceed when previous steps have succeeded. ```typescript async function processUserWorkflow(userId: number) { const userResult = await fetchUser(userId); if (userResult.type !== "SUCCESS") { return userResult; // Propagate error } const validationResult = validateUser(userResult.data.data); if (validationResult.type !== "SUCCESS_VALID") { return validationResult; // Propagate validation error } // Continue with valid user... return Result.ok("WORKFLOW_COMPLETE", validationResult.data); } ``` -------------------------------- ### API Reference: Tagged Result Type Definitions Source: https://github.com/voiys/tagged-result/blob/main/README.md Defines the core types for tagged results, `SuccessResultType` and `ErrorResultType`, for custom `SUCCESS_*` and `ERROR_*` variants, and simplified `DefaultSuccessResultType` and `DefaultErrorResultType` for default `SUCCESS` and `ERROR` results. ```APIDOC SuccessResultType ErrorResultType DefaultSuccessResultType DefaultErrorResultType ``` ```typescript type MySuccessResult = SuccessResultType<"PROCESSED", { message: string }>; // Results in: { type: "SUCCESS_PROCESSED", data: { message: string } } type MyErrorResult = ErrorResultType<"FAILED", { message: string }>; // Results in: { type: "ERROR_FAILED", data: { message: string } } type MyDefaultSuccess = DefaultSuccessResultType<{ message: string }>; // Results in: { type: "SUCCESS", data: { message: string } } type MyDefaultError = DefaultErrorResultType<{ message: string }>; // Results in: { type: "ERROR", data: { message: string } } ``` -------------------------------- ### Best Practice: Use Descriptive Tags for Result Errors in TypeScript Source: https://github.com/voiys/tagged-result/blob/main/README.md Illustrates the importance of using specific and actionable error tags (e.g., 'VALIDATION_FAILED') instead of generic ones (e.g., 'ERROR') when returning `Result.err`. Descriptive tags provide more context, enabling better error handling and debugging. ```typescript // ❌ Not descriptive Result.err("ERROR", { message: "Failed" }); // ✅ Descriptive and actionable Result.err("VALIDATION_FAILED", { field: "email", message: "Invalid email format" }); ``` -------------------------------- ### Best Practice: Use Switch Statements for Exhaustive Result Checking in TypeScript Source: https://github.com/voiys/tagged-result/blob/main/README.md Explains how to use `switch` statements with a union of `Result` types (like `UserOperationResult`) to ensure all possible success and error cases are handled exhaustively. TypeScript's type checking helps identify unhandled cases, promoting robust error management. ```typescript function handleResult(result: UserOperationResult) { switch (result.type) { case "SUCCESS_USER_CREATED": case "SUCCESS_USER_UPDATED": return result.data; // TypeScript knows this is User case "ERROR_USER_NOT_FOUND": case "ERROR_VALIDATION": case "ERROR_PERMISSION_DENIED": case "ERROR": throw new Error(result.data.message); default: // TypeScript will error if we miss a case const exhaustive: never = result; throw new Error('Unhandled result type'); } } ``` -------------------------------- ### API Reference: Result.err method Source: https://github.com/voiys/tagged-result/blob/main/README.md Creates an error result with optional custom type tag following the pattern `"ERROR"` or `"ERROR_${Uppercase}"`. ```APIDOC Result.err(data) Result.err(type, data) ``` ```typescript // Using default "ERROR" type const result1 = Result.err({ message: "Something went wrong" }); // Type: DefaultErrorResultType<{ message: string }> // Using custom type const result2 = Result.err("NOT_FOUND", { resourceId: "user-123" }); // Type: ErrorResultType<"NOT_FOUND", { resourceId: string }> ``` -------------------------------- ### Best Practice: Group Related Result Types with Union Types in TypeScript Source: https://github.com/voiys/tagged-result/blob/main/README.md Shows how to define a union type (`UserOperationResult`) to group related success and error result types. This practice improves type safety, readability, and maintainability for operations that can have multiple distinct outcomes. ```typescript type UserOperationResult = | SuccessResultType<"USER_CREATED" | "USER_UPDATED", User> | ErrorResultType<"USER_NOT_FOUND" | "VALIDATION" | "PERMISSION_DENIED", { message: string }> | DefaultErrorResultType<{ message: string }>; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.