getEnumKey function
Finds the member name of an enum value, string enums included: a readable name for a log or a translation key.
ts
import { getEnumKey } from 'utils';Signature
ts
export function getEnumKey<E extends EnumObject>(enumObject: E, value: unknown): (keyof E & string) | undefinedParameters
| Name | Description |
|---|---|
E | The type of the enum object. |
enumObject | The enum, such as Status. |
value | The value to name. |
Returns
The first member name with this value; undefined when none has it.
Example
ts
enum Status { Idle = 'idle', Running = 'running' }
getEnumKey(Status, 'running'); // 'Running'Tests
Line coverage: 100 %.
- ✅ names the value of a string or numeric enum
- ✅ returns undefined for a value outside the enum
Source
src/enum/get-enum-key.ts (on GitHub)
Uses
EnumObject: Any TypeScript enum, or aconstobject used as one.getEnumEntries: Lists the members of an enum as[name, value]pairs, without the reverse mapping of numeric enums.
Files it needs
src/enum/get-enum-key.ts imports, directly or not:
Source code
ts
import type { EnumObject } from './enum-object';
import { getEnumEntries } from './get-enum-entries';
/**
* Finds the member name of an enum value, string enums included: a readable name for a log or a
* translation key.
*
* @template E - The type of the enum object.
* @param enumObject - The enum, such as `Status`.
* @param value - The value to name.
* @returns The first member name with this value; `undefined` when none has it.
* @example
* enum Status { Idle = 'idle', Running = 'running' }
* getEnumKey(Status, 'running'); // 'Running'
*/
export function getEnumKey<E extends EnumObject>(enumObject: E, value: unknown): (keyof E & string) | undefined {
return getEnumEntries(enumObject).find(([, member]) => member === value)?.[0];
}Test file
ts
import { getEnumKey } from './get-enum-key';
enum Status {
Idle = 'idle',
Running = 'running',
}
enum Level {
Low = 0,
High = 1,
}
describe(getEnumKey, () => {
it('names the value of a string or numeric enum', () => {
expect(getEnumKey(Status, 'running')).toBe('Running');
expect(getEnumKey(Level, 1)).toBe('High');
});
it('returns undefined for a value outside the enum', () => {
expect(getEnumKey(Status, 'stopped')).toBeUndefined();
expect(getEnumKey(Level, '1')).toBeUndefined();
});
});Keywords: get, enum, key, enums, function