Skip to content

getEnumValues function ​

Lists the values of an enum, without the names of the reverse mapping of numeric enums.

ts
import { getEnumValues } from 'utils';

Signature ​

ts
export function getEnumValues<E extends EnumObject>(enumObject: E): E[keyof E][]

Parameters ​

NameDescription
EThe type of the enum object.
enumObjectThe enum to read, such as Direction.

Returns ​

The values, in declaration order.

Example ​

ts
enum Direction { Up, Down }
getEnumValues(Direction); // [0, 1]

Tests ​

Line coverage: 100 %.

  • ✅ lists the values of a numeric enum without the reverse mapping
  • ✅ lists the values of a string enum
  • ✅ lists the values of a const object used as an enum

Source ​

src/enum/get-enum-values.ts (on GitHub)

Uses ​

  • EnumObject: Any TypeScript enum, or a const object used as one.
  • getEnumEntries: Lists the members of an enum as [name, value] pairs, without the reverse mapping of numeric enums.

Used by ​

  • isEnumValue: Checks whether a value is one of the values of an enum, in O(1): the values of each enum are read once.

Files it needs ​

src/enum/get-enum-values.ts imports, directly or not:

Source code
ts
import type { EnumObject } from './enum-object';
import { getEnumEntries } from './get-enum-entries';

/**
 * Lists the values of an enum, without the names of the reverse mapping of numeric enums.
 *
 * @template E - The type of the enum object.
 * @param enumObject - The enum to read, such as `Direction`.
 * @returns The values, in declaration order.
 * @example
 * enum Direction { Up, Down }
 * getEnumValues(Direction); // [0, 1]
 */
export function getEnumValues<E extends EnumObject>(enumObject: E): E[keyof E][] {
  return getEnumEntries(enumObject).map(([, value]) => value);
}
Test file
ts
import { getEnumValues } from './get-enum-values';

enum Direction {
  Up = 0,
  Down = 1,
}

enum Status {
  Idle = 'idle',
  Running = 'running',
}

enum Sparse {
  Low = 1,
  High = 10,
}

describe(getEnumValues, () => {
  it('lists the values of a numeric enum without the reverse mapping', () => {
    expect(getEnumValues(Direction)).toStrictEqual([0, 1]);
    expect(getEnumValues(Sparse)).toStrictEqual([1, 10]);
  });

  it('lists the values of a string enum', () => {
    expect(getEnumValues(Status)).toStrictEqual(['idle', 'running']);
  });

  it('lists the values of a const object used as an enum', () => {
    expect(getEnumValues({ small: 's', large: 'l' } as const)).toStrictEqual(['s', 'l']);
  });
});

Keywords: get, enum, values, enums, function

Generated from the JSDoc of the sources.