Skip to content

Instantly share code, notes, and snippets.

@smitroshin
Created February 2, 2023 14:24
Show Gist options
  • Save smitroshin/64cb52c25d25395560c802a8a3020aec to your computer and use it in GitHub Desktop.
Save smitroshin/64cb52c25d25395560c802a8a3020aec to your computer and use it in GitHub Desktop.
Get from a numeric `enum` just `keys` or just 'values'
/**
* Get from a numeric `enum` just `keys` or just 'values'
*
* Source: https://www.sharooq.com/how-to-access-keys-and-values-of-an-enum-in-typescript
*
* @param target
* @param NumericEnum
* @returns
*/
export const getNumericEnum = (target: "keys" | "values", NumericEnum: Record<any, any>) =>
(target === "values" && Object.values(NumericEnum).filter((v) => !isNaN(Number(v)))) ||
(target === "keys" && Object.keys(NumericEnum).filter((v) => isNaN(Number(v)))) ||
[];
// enum NumericEnum {
// One = 1,
// Two,
// }
// getEnum('keys', NumericEnum) // # [ 'One', 'Two' ]
// getEnum('keys', NumericEnum) // # [ 1, 2 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment