All files / enum get-enum-key.ts

100% Statements 2/2
100% Branches 0/0
100% Functions 2/2
100% Lines 1/1

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19                                8x    
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];
}