TypeScript Enum Utilities
ts-enum-util is a strictly typed utility library designed to enhance the usability and safety of TypeScript enums, as well as string and number literal union types. It provides two core functionalities: Enum Wrapper Utilities and Enum Value Visitor/Mapper. The Enum Wrapper offers type-safe methods for runtime inspection and manipulation of enums, such as retrieving keys, values, performing lookups with validation, and treating enums like arrays or maps. The Value Visitor/Mapper implements a visitor pattern, forcing exhaustive handling of all possible enum or literal union values, similar to a comprehensive switch statement, which helps prevent bugs from unhandled cases. The library is actively maintained, with the current stable version being 4.1.0, and new features or bug fixes are regularly released. Its key differentiators include strong compile-time type safety for enum operations and the exhaustive visitor pattern for robust code.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'getValues') OR similar runtime errors for numeric enums
cause In versions prior to 4.0.1, `ts-enum-util` incorrectly assumed that all numeric enum values were positive integers. This could lead to internal data corruption or failure to correctly process enums containing negative numbers, zero, or floating-point values during runtime operations.fixUpgrade to `ts-enum-util@4.0.1` or newer to obtain fixes for handling non-positive integer enum values correctly. -
Error: Cannot find module 'ts-string-visitor'
cause With the release of `ts-enum-util@4.0.0`, the separate `ts-string-visitor` package was deprecated and its functionality was merged directly into `ts-enum-util`. Direct imports of `ts-string-visitor` will no longer be resolved.fixMigrate your code from using `ts-string-visitor` to utilizing the integrated visitor/mapper functionality available through `$enum.visitValue()` or `$enum.mapValue()` from `ts-enum-util`. -
Type 'any' is not assignable to type 'T' (or similar type incompatibility errors related to EnumWrapper types)
cause In `ts-enum-util` versions prior to `3.0.5` (and `2.0.5`), convenience types like `NumberEnumWrapper`, `StringEnumWrapper`, and `MixedEnumWrapper` were incorrectly defined using the `any` type. This caused a loss of type safety and could lead to compilation errors in strict TypeScript projects.fixUpgrade to `ts-enum-util@3.0.5` (or `2.0.5` for the `2.x` branch) or newer to benefit from corrected and type-safe definitions for these wrapper types.
Warnings
- breaking Version 4.0.0 introduced significant breaking changes by merging the `ts-string-visitor` package's functionality directly into `ts-enum-util`. Users previously relying on `ts-string-visitor` for visitor/mapper patterns will need to migrate their code to use the new `$enum.visitValue()` or `$enum.mapValue()` methods within `ts-enum-util`.
- gotcha Prior to version 4.0.1, `ts-enum-util` made incorrect assumptions about numeric enum values. It could misinterpret non-positive integers (e.g., negative numbers, floating-point numbers) in enums, leading to unexpected behavior or errors during operations like `getKeys()` or `getValues()`.
- gotcha As of version 4.0.2, the `typescript` peer dependency has been removed. While this simplifies installation for many projects, it means `ts-enum-util` no longer directly enforces a TypeScript version through its `package.json`. Projects relying on this peer dependency for tooling or CI/CD pipelines might need to adjust their configuration.
- gotcha The library has specific requirements for supported TypeScript versions. Always consult the 'Requirements' section in the `ts-enum-util` README to ensure compatibility with your project's TypeScript version, as using an unsupported version can lead to compilation issues.
Install
-
npm install ts-enum-util -
yarn add ts-enum-util -
pnpm add ts-enum-util
Imports
- $enum
const $enum = require('ts-enum-util').$enum;import { $enum } from 'ts-enum-util'; - NumberEnumWrapper
import type { NumberEnumWrapper } from 'ts-enum-util'; - EnumWrapper
import type { EnumWrapper } from 'ts-enum-util';
Quickstart
import { $enum } from 'ts-enum-util';
enum Color {
Red = 0,
Green = 1,
Blue = 2
}
enum Status {
Active = 'ACTIVE',
Inactive = 'INACTIVE',
Pending = 'PENDING'
}
// Use $enum() as a function to access Enum Wrapper Utilities
const colorValues = $enum(Color).getValues();
console.log('Color Values:', colorValues); // Expected: [0, 1, 2]
const colorKeys = $enum(Color).getKeys();
console.log('Color Keys:', colorKeys); // Expected: ['Red', 'Green', 'Blue']
// Check if a value is valid for an enum at runtime
const isValidRed = $enum(Color).isValue(0);
console.log('Is 0 a valid Color value?', isValidRed); // Expected: true
// Use $enum.visitValue() for exhaustive handling of enum states
function describeStatus(status: Status): string {
return $enum.visitValue(status).with({
[Status.Active]: () => 'The item is currently active.',
[Status.Inactive]: () => 'The item is not active.',
[Status.Pending]: () => 'The item is awaiting activation.'
});
}
console.log('Status description for Active:', describeStatus(Status.Active));