### Install @dovocode/enum Source: https://github.com/dovocode/enum/blob/main/README.md Commands to install the @dovocode/enum package using npm, yarn, or pnpm. This package provides type-safe and immutable enums for TypeScript and JavaScript. ```bash npm install @dovocode/enum # or yarn add @dovocode/enum # or pnpm add @dovocode/enum ``` -------------------------------- ### Usage Examples for @dovocode/enum Source: https://github.com/dovocode/enum/blob/main/README.md Demonstrates how to create and use type-safe enums with @dovocode/enum. Includes examples for array-based, numeric object, and string object enums, showcasing type inference, runtime immutability, and strict typing in function parameters. ```typescript import { enumOf, type Enum } from '@dovocode/enum'; // Array-based enum const Colors = enumOf(['RED', 'GREEN', 'BLUE']); // { readonly RED: 0; readonly GREEN: 1; readonly BLUE: 2 } const color: Enum = Colors.RED; // Only 0, 1, or 2 allowed // Numeric object enum const Priorities = enumOf({ LOW: 0, MEDIUM: 1, HIGH: 2, }); // { readonly LOW: 0; readonly MEDIUM: 1; readonly HIGH: 2 } const priority: Enum = Priorities.HIGH; // String object enum const HttpMethods = enumOf({ GET: 'GET', POST: 'POST', PUT: 'PUT', DELETE: 'DELETE', }); // { readonly GET: 'GET'; ... } const method: Enum = HttpMethods.GET; // Immutability at runtime // @ts-expect-error HttpMethods.GET = 'INVALID'; // ❌ Error: property is readonly // Strictly typed in function parameters function handleRequest(method: Enum) { switch (method) { case HttpMethods.GET: return 'Handling GET request'; case HttpMethods.POST: return 'Handling POST request'; } } ``` -------------------------------- ### Creating Array-Based Enums Source: https://context7.com/dovocode/enum/llms.txt Demonstrates how to create an enum from an array of strings, where string keys map to sequential numeric indices. Includes examples of type safety and runtime immutability. ```APIDOC ## Creating Array-Based Enums Array-based enums map string keys to their array indices, providing a simple way to create sequential numeric enums. ### Method `enumOf()` ### Parameters #### Request Body - **values** (string[]) - Required - An array of strings to be used as enum keys. ### Request Example ```typescript import { enumOf, type Enum } from '@dovocode/enum'; // Define enum from array of strings const Colors = enumOf(['RED', 'GREEN', 'BLUE']); ``` ### Response #### Success Response (Object) An immutable object where keys are the provided strings and values are their corresponding indices. - **RED** (number) - The index of 'RED' (0). - **GREEN** (number) - The index of 'GREEN' (1). - **BLUE** (number) - The index of 'BLUE' (2). #### Response Example ```json { "RED": 0, "GREEN": 1, "BLUE": 2 } ``` ### Type Safety Example ```typescript // Type-safe function parameters function setColor(color: Enum) { console.log(`Setting color to: ${color}`); } setColor(Colors.RED); // ✅ OK - passes 0 setColor(0); // ✅ OK - 0 is valid // setColor(3); // ❌ TypeScript error - 3 is not 0 | 1 | 2 ``` ### Immutability Example ```typescript // Immutability at runtime try { Colors.RED = 99; // ❌ Runtime error - cannot modify frozen object } catch (error) { console.error('Cannot modify enum:', error); } ``` ``` -------------------------------- ### Typing Example with @dovocode/enum Source: https://github.com/dovocode/enum/blob/main/README.md Illustrates how to use the `Enum` utility type provided by @dovocode/enum to define specific types for enum values. This ensures type safety when assigning or passing enum values. ```typescript const Colors = enumOf(['RED', 'GREEN', 'BLUE']); type ColorValue = Enum; // 0 | 1 | 2 const Methods = enumOf({ GET: 'GET', POST: 'POST' }); type HttpMethod = Enum; // "GET" | "POST" function paint(color: ColorValue) {} paint(Colors.RED); // ✅ OK // paint(3); // ❌ Error ``` -------------------------------- ### Create Numeric Object Enum in TypeScript Source: https://context7.com/dovocode/enum/llms.txt Shows how to create a numeric enum with explicit value assignments using `enumOf`. This is useful for status codes or flags. The example includes type extraction for `Enum` and usage within an `ApiResponse` interface. ```typescript import { enumOf, type Enum } from '@dovocode/enum'; // Define enum with explicit numeric values const HttpStatus = enumOf({ OK: 200, CREATED: 201, BAD_REQUEST: 400, UNAUTHORIZED: 401, NOT_FOUND: 404, SERVER_ERROR: 500 }); // Type extraction type StatusCode = Enum; // 200 | 201 | 400 | 401 | 404 | 500 // Use in API response handler interface ApiResponse { status: StatusCode; data: T; } function handleResponse(response: ApiResponse) { switch (response.status) { case HttpStatus.OK: return { success: true, data: response.data }; case HttpStatus.CREATED: return { success: true, created: true, data: response.data }; case HttpStatus.NOT_FOUND: return { success: false, error: 'Resource not found' }; case HttpStatus.SERVER_ERROR: return { success: false, error: 'Server error occurred' }; default: return { success: false, error: 'Unknown status' }; } } // Example usage const result = handleResponse({ status: HttpStatus.OK, data: { id: 1, name: 'John' } }); console.log(result); // { success: true, data: { id: 1, name: 'John' } } ``` -------------------------------- ### Create String Object Enum in TypeScript Source: https://context7.com/dovocode/enum/llms.txt Illustrates creating a string-based enum using `enumOf`, mapping keys to string values. This is ideal for HTTP methods or event names. The example shows type extraction (`Enum`) and usage in a `makeRequest` function with type safety. ```typescript import { enumOf, type Enum } from '@dovocode/enum'; // Define string-based enum const HttpMethod = enumOf({ GET: 'GET', POST: 'POST', PUT: 'PUT', DELETE: 'DELETE', PATCH: 'PATCH' }); // Extract union type type Method = Enum; // "GET" | "POST" | "PUT" | "DELETE" | "PATCH" // Use in request configuration interface RequestConfig { url: string; method: Method; headers?: Record; body?: unknown; } function makeRequest(config: RequestConfig): Promise { const { url, method, headers, body } = config; const options: RequestInit = { method: method, headers: { 'Content-Type': 'application/json', ...headers } }; if (body && method !== HttpMethod.GET) { options.body = JSON.stringify(body); } return fetch(url, options); } // Example usage makeRequest({ url: 'https://api.example.com/users', method: HttpMethod.POST, // ✅ Type-safe body: { name: 'Alice', email: 'alice@example.com' } }).then(response => console.log('User created:', response.status)); // Invalid method caught by TypeScript makeRequest({ url: 'https://api.example.com/users', method: 'INVALID' // ❌ TypeScript error }); ``` -------------------------------- ### Runtime Enum Value Validation with Symbol Properties (TypeScript) Source: https://context7.com/dovocode/enum/llms.txt Demonstrates how to use hidden symbol properties like 'keys' and 'values' from '@dovocode/enum' to validate enum members at runtime. This prevents polluting the enum interface and allows for safe type narrowing in functions. It includes examples for checking value existence and key existence. ```typescript import { enumOf, keys, values, type Enum } from '@dovocode/enum'; // Create enum const UserRole = enumOf({ ADMIN: 'admin', MODERATOR: 'moderator', USER: 'user', GUEST: 'guest' }); // Access keys and values at runtime console.log(UserRole[keys]); // ['ADMIN', 'MODERATOR', 'USER', 'GUEST'] console.log(UserRole[values]); // ['admin', 'moderator', 'user', 'guest'] // Validate if a value exists in enum function isValidRole(role: string): role is Enum { return UserRole[values].includes(role); } // Safe type narrowing function assignRole(userInput: string) { if (isValidRole(userInput)) { // userInput is now typed as Enum console.log(`Valid role: ${userInput}`); return userInput; } throw new Error(`Invalid role: ${userInput}`); } // Example usage assignRole('admin'); // ✅ "Valid role: admin" assignRole('superuser'); // ❌ Error: "Invalid role: superuser" // Check if key exists function hasRoleKey(key: string): key is keyof typeof UserRole { return UserRole[keys].includes(key); } console.log(hasRoleKey('ADMIN')); // true console.log(hasRoleKey('OWNER')); // false ``` -------------------------------- ### Creating String Object Enums Source: https://context7.com/dovocode/enum/llms.txt Shows how to create enums where string keys map to string values. Ideal for HTTP methods, event names, or other string-based constants. ```APIDOC ## Creating String Object Enums String object enums map keys to string values, ideal for HTTP methods, event names, or any string-based constants. ### Method `enumOf()` ### Parameters #### Request Body - **values** (Record) - Required - An object where keys are strings and values are strings to be used as enum keys and values. ### Request Example ```typescript import { enumOf, type Enum } from '@dovocode/enum'; // Define string-based enum const HttpMethod = enumOf({ GET: 'GET', POST: 'POST', PUT: 'PUT', DELETE: 'DELETE', PATCH: 'PATCH' }); ``` ### Response #### Success Response (Object) An immutable object where keys are the provided strings and values are their corresponding assigned strings. - **GET** (string) - "GET" - **POST** (string) - "POST" - **PUT** (string) - "PUT" - **DELETE** (string) - "DELETE" - **PATCH** (string) - "PATCH" #### Response Example ```json { "GET": "GET", "POST": "POST", "PUT": "PUT", "DELETE": "DELETE", "PATCH": "PATCH" } ``` ### Type Extraction Example ```typescript // Extract union type type Method = Enum; // "GET" | "POST" | "PUT" | "DELETE" | "PATCH" ``` ### Usage Example ```typescript interface RequestConfig { url: string; method: Method; headers?: Record; body?: unknown; } function makeRequest(config: RequestConfig): Promise { const { url, method, headers, body } = config; const options: RequestInit = { method: method, headers: { 'Content-Type': 'application/json', ...headers } }; if (body && method !== HttpMethod.GET) { options.body = JSON.stringify(body); } return fetch(url, options); } // Example usage makeRequest({ url: 'https://api.example.com/users', method: HttpMethod.POST, // ✅ Type-safe body: { name: 'Alice', email: 'alice@example.com' } }).then(response => console.log('User created:', response.status)); // Invalid method caught by TypeScript // makeRequest({ // url: 'https://api.example.com/users', // method: 'INVALID' // ❌ TypeScript error // }); ``` ``` -------------------------------- ### Database Model Integration with Enums in TypeScript Source: https://context7.com/dovocode/enum/llms.txt Illustrates how to integrate Dovocode enums with database models and ORMs for enhanced data consistency. It shows defining a user status enum, creating a type-safe User interface, and implementing a UserRepository with methods for creating, updating, and querying users based on their status. This ensures type safety throughout database operations. ```typescript import { enumOf, type Enum, values } from '@dovocode/enum'; // Define user status enum const UserStatus = enumOf({ ACTIVE: 'active', INACTIVE: 'inactive', SUSPENDED: 'suspended', DELETED: 'deleted' }); type Status = Enum; // Database model interface interface User { id: number; username: string; email: string; status: Status; createdAt: Date; updatedAt: Date; } // Type-safe database operations class UserRepository { async create(userData: Omit): Promise { // Validate status before insert if (!UserStatus[values].includes(userData.status)) { throw new Error(`Invalid status: ${userData.status}`); } // Simulate database insert return { ...userData, id: Math.floor(Math.random() * 10000), createdAt: new Date(), updatedAt: new Date() }; } async updateStatus(userId: number, newStatus: Status): Promise { // Type-safe status update console.log(`Updating user ${userId} status to ${newStatus}`); // Simulate database update return { id: userId, username: 'john_doe', email: 'john@example.com', status: newStatus, createdAt: new Date(Date.now() - 86400000), updatedAt: new Date() }; } async findByStatus(status: Status): Promise { // Type-safe query filtering console.log(`Finding users with status: ${status}`); return []; } } // Example usage async function main() { const repo = new UserRepository(); // Create new user const newUser = await repo.create({ username: 'alice', email: 'alice@example.com', status: UserStatus.ACTIVE // ✅ Type-safe }); console.log('Created user:', newUser); // Update user status const updated = await repo.updateStatus(newUser.id, UserStatus.SUSPENDED); console.log('Updated user:', updated); // Query by status const activeUsers = await repo.findByStatus(UserStatus.ACTIVE); console.log('Active users:', activeUsers.length); } main().catch(console.error); ``` -------------------------------- ### State Machine Implementation with Enums (TypeScript) Source: https://context7.com/dovocode/enum/llms.txt Illustrates using Dovocode enums to build type-safe state machines. It defines states and valid transitions using a `Record` and manages state changes within a class, ensuring only permissible transitions occur. This pattern is useful for workflow management. ```typescript import { enumOf, type Enum, values } from '@dovocode/enum'; // Define states and transitions const OrderState = enumOf({ PENDING: 'PENDING', CONFIRMED: 'CONFIRMED', PROCESSING: 'PROCESSING', SHIPPED: 'SHIPPED', DELIVERED: 'DELIVERED', CANCELLED: 'CANCELLED' }); type State = Enum; // Define valid state transitions const stateTransitions: Record = { [OrderState.PENDING]: [OrderState.CONFIRMED, OrderState.CANCELLED], [OrderState.CONFIRMED]: [OrderState.PROCESSING, OrderState.CANCELLED], [OrderState.PROCESSING]: [OrderState.SHIPPED, OrderState.CANCELLED], [OrderState.SHIPPED]: [OrderState.DELIVERED], [OrderState.DELIVERED]: [], [OrderState.CANCELLED]: [] }; // Order management system class Order { private currentState: State; constructor(public id: string) { this.currentState = OrderState.PENDING; } getState(): State { return this.currentState; } canTransitionTo(newState: State): boolean { return stateTransitions[this.currentState].includes(newState); } transition(newState: State): void { if (!this.canTransitionTo(newState)) { throw new Error( `Invalid transition from ${this.currentState} to ${newState}` ); } console.log(`Order ${this.id}: ${this.currentState} → ${newState}`); this.currentState = newState; } cancel(): void { if (this.currentState === OrderState.DELIVERED) { throw new Error('Cannot cancel delivered order'); } this.transition(OrderState.CANCELLED); } } // Example workflow const order = new Order('ORD-001'); console.log(order.getState()); // PENDING order.transition(OrderState.CONFIRMED); // ✅ OK order.transition(OrderState.PROCESSING); // ✅ OK order.transition(OrderState.SHIPPED); // ✅ OK order.transition(OrderState.DELIVERED); // ✅ OK // Invalid transition try { order.transition(OrderState.PENDING); // ❌ Error: Invalid transition } catch (error) { console.error(error); } ``` -------------------------------- ### Creating Numeric Object Enums Source: https://context7.com/dovocode/enum/llms.txt Illustrates how to create enums with explicit numeric values assigned to string keys. Useful for status codes, priority levels, or flags. ```APIDOC ## Creating Numeric Object Enums Numeric object enums allow explicit numeric value assignments for each key, useful for status codes, priority levels, or flags. ### Method `enumOf()` ### Parameters #### Request Body - **values** (Record) - Required - An object where keys are strings and values are numbers to be used as enum keys and values. ### Request Example ```typescript import { enumOf, type Enum } from '@dovocode/enum'; // Define enum with explicit numeric values const HttpStatus = enumOf({ OK: 200, CREATED: 201, BAD_REQUEST: 400, UNAUTHORIZED: 401, NOT_FOUND: 404, SERVER_ERROR: 500 }); ``` ### Response #### Success Response (Object) An immutable object where keys are the provided strings and values are their corresponding assigned numbers. - **OK** (number) - 200 - **CREATED** (number) - 201 - **BAD_REQUEST** (number) - 400 - **UNAUTHORIZED** (number) - 401 - **NOT_FOUND** (number) - 404 - **SERVER_ERROR** (number) - 500 #### Response Example ```json { "OK": 200, "CREATED": 201, "BAD_REQUEST": 400, "UNAUTHORIZED": 401, "NOT_FOUND": 404, "SERVER_ERROR": 500 } ``` ### Type Extraction Example ```typescript // Type extraction type StatusCode = Enum; // 200 | 201 | 400 | 401 | 404 | 500 ``` ### Usage Example ```typescript interface ApiResponse { status: StatusCode; data: T; } function handleResponse(response: ApiResponse) { switch (response.status) { case HttpStatus.OK: return { success: true, data: response.data }; case HttpStatus.CREATED: return { success: true, created: true, data: response.data }; case HttpStatus.NOT_FOUND: return { success: false, error: 'Resource not found' }; case HttpStatus.SERVER_ERROR: return { success: false, error: 'Server error occurred' }; default: return { success: false, error: 'Unknown status' }; } } // Example usage const result = handleResponse({ status: HttpStatus.OK, data: { id: 1, name: 'John' } }); console.log(result); // { success: true, data: { id: 1, name: 'John' } } ``` ``` -------------------------------- ### Enum Definition and Error Handling in TypeScript Source: https://context7.com/dovocode/enum/llms.txt Demonstrates the creation of array, numeric, and string enums using the `enumOf` function. It also showcases comprehensive error handling for various invalid enum definitions, such as empty arrays, arrays with non-strings, empty objects, and incorrect input types. This ensures robust enum creation. ```typescript import { enumOf } from '@dovocode/enum'; // Valid definitions try { const ValidArray = enumOf(['OPTION_A', 'OPTION_B']); console.log('Array enum created:', ValidArray); const ValidNumeric = enumOf({ LOW: 1, MEDIUM: 2, HIGH: 3 }); console.log('Numeric enum created:', ValidNumeric); const ValidString = enumOf({ SUCCESS: 'success', ERROR: 'error' }); console.log('String enum created:', ValidString); } catch (error) { console.error('Unexpected error:', error); } // Invalid definitions - will throw errors try { // Empty array const EmptyArray = enumOf([]); } catch (error) { console.error('Empty array error:', error.message); // "Invalid enum definition: expected an array of strings..." } try { // Array with non-strings const InvalidArray = enumOf([1, 2, 3] as any); } catch (error) { console.error('Invalid array error:', error.message); // "Invalid enum definition: expected an array of strings..." } try { // Empty object const EmptyObject = enumOf({} as any); } catch (error) { console.error('Empty object error:', error.message); // "Invalid enum definition: expected a plain object..." } try { // Invalid input type const InvalidInput = enumOf(123 as any); } catch (error) { console.error('Invalid input error:', error.message); // "Invalid enum definition: expected an array of strings or a plain object..." } try { // Mixed types in object (not supported) const MixedObject = enumOf({ A: 1, B: 'two' } as any); console.log('Mixed object created:', MixedObject); } catch (error) { console.error('Mixed type error:', error.message); } ``` -------------------------------- ### Create Array-Based Enum in TypeScript Source: https://context7.com/dovocode/enum/llms.txt Demonstrates creating a type-safe, immutable enum from an array of strings using `enumOf`. This maps string keys to their sequential numeric indices. It highlights type-safe function parameters and runtime immutability checks. ```typescript import { enumOf, type Enum } from '@dovocode/enum'; // Define enum from array of strings const Colors = enumOf(['RED', 'GREEN', 'BLUE']); // Access enum values console.log(Colors.RED); // 0 console.log(Colors.GREEN); // 1 console.log(Colors.BLUE); // 2 // Type-safe function parameters function setColor(color: Enum) { console.log(`Setting color to: ${color}`); } setColor(Colors.RED); // ✅ OK - passes 0 setColor(0); // ✅ OK - 0 is valid setColor(3); // ❌ TypeScript error - 3 is not 0 | 1 | 2 // Immutability at runtime try { Colors.RED = 99; // ❌ Runtime error - cannot modify frozen object } catch (error) { console.error('Cannot modify enum:', error); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.