UNPKG

ts-cast

Version:
19 lines (18 loc) 756 B
import { isEmpty } from './guards'; import { throwTypeError } from './throw-type-error'; const applyRule = (value, context, reportError) => (rule) => { const error = rule(value); if (!error) return; reportError(`${context ? `${context} should be` : 'expected value is'} ${error} but received ${value}.`, context); }; export const restrict = (caster, rules) => { const validator = (value, context, reportError = throwTypeError) => { const typedValue = caster(value, context, reportError); if (!isEmpty(typedValue)) rules.forEach(applyRule(typedValue, context, reportError)); return typedValue; }; Reflect.defineProperty(validator, 'name', { value: caster.name }); return validator; };