Skip to content

Instantly share code, notes, and snippets.

@levchenkod
Created April 22, 2024 01:47
Show Gist options
  • Save levchenkod/1ac4b074979f463a9150d3ac4a2dad12 to your computer and use it in GitHub Desktop.
Save levchenkod/1ac4b074979f463a9150d3ac4a2dad12 to your computer and use it in GitHub Desktop.
Safely convert enum to array
import enumToArray from "./enumToArray";
enum Numbers {
One = 'One',
Two = 'Two',
Three = 'Three'
};
enum Empty {}
describe('enumToArray', () => {
test('simple enum', () => {
const expectedResult = ['One', 'Two', 'Three'];
expect(enumToArray(Numbers))
.toStrictEqual(expectedResult);
});
test('Empty enum', () => {
const expectedResult:any[] = [];
expect(enumToArray(Empty))
.toStrictEqual(expectedResult);
});
});
/**
* @description Safely convert enum object to array of values
* IMPORTANT: to avoid index-key bugs use eslint rule "@typescript-eslint/prefer-enum-initializers"
* more details here: https://www.typescriptlang.org/docs/handbook/enums.html
*/
const enumToArray = (enumObject: object):Array<string> => {
let result:Array<string> = [];
for (const key in enumObject) {
if (
enumObject.hasOwnProperty(key)
) {
const value = enumObject[key as keyof object];
result.push(value);
}
}
return result;
}
export default enumToArray;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment