Enum Utilities
Paquete: @tiendana/utils
Funciones para trabajar con enums de TypeScript: obtener valores por clave y claves por valor.
Firmas
function getEnumValueByKey<T extends Record<string, string | number>>(
enumType: T,
key: string
): T[keyof T] | undefined
function getEnumKeyByValue<T>(
enumObj: T,
value?: T[keyof T]
): string | undefined
Uso
getEnumValueByKey
import { getEnumValueByKey } from '@tiendana/utils';
enum Status {
Pending = 'pending',
Active = 'active',
Completed = 'completed'
}
getEnumValueByKey(Status, 'Active'); // 'active'
getEnumValueByKey(Status, 'Pending'); // 'pending'
getEnumValueByKey(Status, 'Invalid'); // undefined
getEnumKeyByValue
import { getEnumKeyByValue } from '@tiendana/utils';
enum Priority {
Low = 1,
Medium = 2,
High = 3
}
getEnumKeyByValue(Priority, 2); // 'Medium'
getEnumKeyByValue(Priority, 3); // 'High'
getEnumKeyByValue(Priority, 99); // undefined
Casos de Uso
- Parsear valores de APIs a enums
- Validación de inputs contra enums
- Mapeo bidireccional de enums
- Debugging y logging de valores de enum
Notas Técnicas
- Type-safe: Genéricos preservan tipos
- Safe: Retorna
undefinedsi no encuentra match - String/Number enums: Soporta ambos tipos
Ver También
- strToNumber - Conversión segura de strings