getEnumEntries function
Lists the members of an enum as [name, value] pairs, without the reverse mapping of numeric enums.
ts
import { getEnumEntries } from 'utils';Signature
ts
export function getEnumEntries<E extends EnumObject>(enumObject: E): [key: keyof E & string, value: E[keyof E]][]Parameters
| Name | Description |
|---|---|
E | The type of the enum object. |
enumObject | The enum to read, such as Direction. |
Returns
The [name, value] pairs, in declaration order.
Example
ts
enum Direction { Up, Down }
getEnumEntries(Direction); // [['Up', 0], ['Down', 1]]Tests
Line coverage: 100 %.
- ✅ lists name and value pairs without the reverse mapping
Source
src/enum/get-enum-entries.ts (on GitHub)
Uses
EnumObject: Any TypeScript enum, or aconstobject used as one.
Used by
getEnumKey: Finds the member name of an enum value, string enums included: a readable name for a log or a translation key.getEnumKeys: Lists the member names of an enum, without the reverse mapping of numeric enums.getEnumValues: Lists the values of an enum, without the names of the reverse mapping of numeric enums.parseEnumValue: Reads an enum member from a text, such as a query parameter:'1'gives the member of value1.
Files it needs
src/enum/get-enum-entries.ts imports, directly or not:
Source code
ts
import type { EnumObject } from './enum-object';
/**
* Lists the members of an enum as `[name, value]` pairs, without 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 `[name, value]` pairs, in declaration order.
* @example
* enum Direction { Up, Down }
* getEnumEntries(Direction); // [['Up', 0], ['Down', 1]]
*/
export function getEnumEntries<E extends EnumObject>(enumObject: E): [key: keyof E & string, value: E[keyof E]][] {
const entries: [keyof E & string, E[keyof E]][] = [];
for (const [key, value] of Object.entries(enumObject)) {
if (String(Number(key)) !== key) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- A value of `E`, read from `E`.
entries.push([key, value as E[keyof E]]);
}
}
return entries;
}Test file
ts
import { getEnumEntries } from './get-enum-entries';
enum Direction {
Up = 0,
Down = 1,
}
enum Status {
Idle = 'idle',
Running = 'running',
}
describe(getEnumEntries, () => {
it('lists name and value pairs without the reverse mapping', () => {
expect(getEnumEntries(Direction)).toStrictEqual([
['Up', 0],
['Down', 1],
]);
expect(getEnumEntries(Status)).toStrictEqual([
['Idle', 'idle'],
['Running', 'running'],
]);
});
});Keywords: get, enum, entries, enums, function