enum-pro
v1.0.3
Published
A powerful enum utility for TypeScript/JavaScript with full type inference.
Downloads
341
Maintainers
Readme
Enum Pro
A powerful, type-safe enum utility for TypeScript and JavaScript.
Features
- Full TypeScript Support: strict type inference for enum keys and values.
- Runtime Helpers:
getOptions(),getLabel(),hasValue()attached directly to the enum object. - Immutable: The resulting enum object is deeply frozen.
- Universal: Works in Node.js and Browser (CJS & ESM).
Installation
npm install enum-proUsage
Basic Usage
import { toEnum } from 'enum-pro'
const STATUS = toEnum({
PENDING: { label: 'Pending', value: 0 },
SUCCESS: { label: 'Success', value: 1 },
FAILED: { label: 'Failed', value: 2 }
})
// Access properties as usual
console.log(STATUS.PENDING.value) // 0
// Use helper methods
console.log(STATUS.getOptions())
// [
// { name: 'PENDING', label: 'Pending', value: 0 },
// { name: 'SUCCESS', label: 'Success', value: 1 },
// { name: 'FAILED', label: 'Failed', value: 2 }
// ]
console.log(STATUS.getLabel(1)) // 'Success'
console.log(STATUS.hasValue(99)) // falseType Inference
enum-pro automatically infers the types of your enum.
type StatusEnum = typeof STATUS
// Enum<{ PENDING: { label: string; value: number; }; ... }>API
toEnum(data)
Converts a plain object into an enhanced Enum object.
- data: An object where keys are enum names and values are option objects (must have
valueproperty,labelis recommended).
Enum Methods
Every enum created with toEnum has these methods:
getOptions(): Returns an array of all options, with an addednameproperty corresponding to the key.getLabel(value): Returns the label for a given value.getOption(value): Returns the full option object for a given value.hasValue(value): Returnstrueif the value exists in the enum.
License
ISC
