Last active
September 2, 2022 10:58
-
-
Save temoncher/3c0db326cb02ac0dbe3abfde11ddecac to your computer and use it in GitHub Desktop.
`isEnum` typeguard
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
| export const isEnum = <T extends string | number, TEnumValue extends string>(enumVariable: { [key in T]: TEnumValue }) => { | |
| const enumValues = Object.values(enumVariable); | |
| return (value: unknown): value is TEnumValue => (typeof value === 'string' || typeof value === 'number') && enumValues.includes(value); | |
| }; | |
| // with number indexes not allowed | |
| export const isEnum = <T extends string, TEnumValue extends string>(enumVariable: { [key in T]: TEnumValue }) => { | |
| const enumValues = Object.values(enumVariable); | |
| return (value: unknown): value is TEnumValue => typeof value === 'string' && enumValues.includes(value); | |
| }; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment