Skip to content

Instantly share code, notes, and snippets.

@temoncher
Last active September 2, 2022 10:58
Show Gist options
  • Select an option

  • Save temoncher/3c0db326cb02ac0dbe3abfde11ddecac to your computer and use it in GitHub Desktop.

Select an option

Save temoncher/3c0db326cb02ac0dbe3abfde11ddecac to your computer and use it in GitHub Desktop.
`isEnum` typeguard
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