Skip to content

Instantly share code, notes, and snippets.

@ayoayco
Last active January 13, 2024 08:41
Show Gist options
  • Save ayoayco/e88e871783373cce97caebfb47c7896d to your computer and use it in GitHub Desktop.
Save ayoayco/e88e871783373cce97caebfb47c7896d to your computer and use it in GitHub Desktop.
/**
* A typeguard to check if a value is valid entry in an Enum.
* If it passes, the value will be typed as the enum
* @param value value to check
* @param enumType Enum to check against
* @returns boolean and assigns type to value
* @example
* ```ts
* enum TestEnum {
* Value1 = 'Value1',
* Value2 = 'Value2',
* }
*
* const result = isInEnum('Value1', TestEnum);
* // result is true
*
* const value = 'Value1'; // value is of type string
* if(isInEnum(value, TestEnum)) {
* doSomething(value); // value is of type TestEnum now. You're welcome.
* }
* ```
*/
export function isInEnum<T>(value: unknown, enumType: T): value is T[keyof T] {
return Object.values(enumType).includes(value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment