typedash
Version:
modern, type-safe collection of utility functions
32 lines (30 loc) • 963 B
JavaScript
//#region src/functions/createTypeGuard/createTypeGuard.ts
/**
* Creates a type guard that checks if the given type is assignable to the given type.
* @param values The values to check against.
* @template {TInput} The type to check against, `unknown` by default. Pass in if you want to have a narrowed type for the type predicate (e.g. `string`).
* @returns A type guard that checks if the given type is assignable to the given type.
* @example
* ```ts
* const isValidValue = createTypeGuard(['foo', 'bar']);
*
* const value: unknown = '...';
* if (isValidValue(value)) {
* // ✅ value is of type `'foo' | 'bar'`
* }
* ```
*/
function createTypeGuard(values) {
const setValues = new Set(values);
return function predicate(v) {
return setValues.has(v);
};
}
//#endregion
Object.defineProperty(exports, 'createTypeGuard', {
enumerable: true,
get: function () {
return createTypeGuard;
}
});
//# sourceMappingURL=createTypeGuard-CC3eS9IQ.cjs.map