guardz
Version:
A simple and lightweight TypeScript type guard library for runtime type validation.
53 lines (52 loc) • 1.36 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isEnum = isEnum;
const isOneOf_1 = require("./isOneOf");
/**
* Creates a type guard that checks if a value matches any value from an enum.
*
* This function extracts all values from an enum object and creates a type guard
* that validates against any of those values.
*
* @template T - The enum type
* @param enumValue - The enum object to check against
* @returns A type guard function that validates enum values
*
* @example
* ```typescript
* import { isEnum } from 'guardz';
*
* enum Color {
* RED = "red",
* GREEN = "green",
* BLUE = "blue"
* }
*
* enum Status {
* PENDING = 0,
* APPROVED = 1,
* REJECTED = 2
* }
*
* const isColor = isEnum(Color);
* const isStatus = isEnum(Status);
*
* console.log(isColor("red")); // true
* console.log(isColor("blue")); // true
* console.log(isColor("yellow")); // false
* console.log(isStatus(1)); // true
* console.log(isStatus(5)); // false
*
* // With type narrowing
* const data: unknown = getUserInput();
* if (isColor(data)) {
* // data is now typed as Color
* console.log(`Selected color: ${data}`);
* }
* ```
*/
function isEnum(enumValue) {
return function (value, config) {
return (0, isOneOf_1.isOneOf)(...Object.values(enumValue))(value, config);
};
}