getEnumKeys function
Lists the member names of an enum, without the reverse mapping of numeric enums.
ts
import { getEnumKeys } from 'utils';Signature
ts
export function getEnumKeys<E extends EnumObject>(enumObject: E): (keyof E & string)[]Parameters
| Name | Description |
|---|---|
E | The type of the enum object. |
enumObject | The enum to read, such as Direction. |
Returns
The member names, in declaration order.
Example
ts
enum Direction { Up, Down }
getEnumKeys(Direction); // ['Up', 'Down']Tests
Line coverage: 100 %.
- ✅ lists the member names without the reverse mapping
Source
src/enum/get-enum-keys.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-keys.ts imports, directly or not:
Source code
ts
import type { EnumObject } from './enum-object';
import { getEnumEntries } from './get-enum-entries';
/**
* Lists the member names of an enum, 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 member names, in declaration order.
* @example
* enum Direction { Up, Down }
* getEnumKeys(Direction); // ['Up', 'Down']
*/
export function getEnumKeys<E extends EnumObject>(enumObject: E): (keyof E & string)[] {
return getEnumEntries(enumObject).map(([key]) => key);
}Test file
ts
import { getEnumKeys } from './get-enum-keys';
enum Direction {
Up = 0,
Down = 1,
}
enum Status {
Idle = 'idle',
}
describe(getEnumKeys, () => {
it('lists the member names without the reverse mapping', () => {
expect(getEnumKeys(Direction)).toStrictEqual(['Up', 'Down']);
expect(getEnumKeys(Status)).toStrictEqual(['Idle']);
});
});Keywords: get, enum, keys, enums, function