Last active
April 9, 2022 05:39
-
-
Save serg06/c83e725c38d60d62536bf850baceb0a9 to your computer and use it in GitHub Desktop.
[TypeScript] Iterating over enums
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
function isStringEnum<T extends Record<string, string | number>>(t: T): boolean { | |
return typeof Object.values(t).pop() === 'string'; | |
} | |
export function enumKeys<T extends Record<string, string | number>>(t: T): (keyof T)[] { | |
return isStringEnum(t) ? Object.keys(t) : Object.keys(t).slice(0, Object.keys(t).length / 2); | |
} | |
export function enumValues<T extends Record<string, string>>(t: T): string[]; | |
export function enumValues<T extends Record<string, string | number>>(t: T): number[]; | |
export function enumValues<T extends Record<string, string | number>>(t: T): string[] | number[] { | |
if (isStringEnum(t)) { | |
return Object.values(t) as string[]; | |
} else { | |
return Object.values(t).slice(Object.values(t).length / 2) as number[]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment