Last active
January 13, 2024 08:41
-
-
Save ayoayco/e88e871783373cce97caebfb47c7896d to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* 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