TypeScript Enum Utilities

4.1.0 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

Demonstrates importing the `$enum` utility, defining enums, and using wrapper methods like `getValues()`, `getKeys()`, `isValue()`, and the `visitValue()` pattern for exhaustive enum value handling.

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));

view raw JSON →