Created
April 22, 2024 01:47
-
-
Save levchenkod/1ac4b074979f463a9150d3ac4a2dad12 to your computer and use it in GitHub Desktop.
Safely convert enum to array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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