UNPKG

ts-cast

Version:
26 lines (25 loc) 1.06 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.restrict = void 0; var guards_1 = require("./guards"); var throw_type_error_1 = require("./throw-type-error"); var applyRule = function (value, context, reportError) { return function (rule) { var error = rule(value); if (!error) return; reportError("".concat(context ? "".concat(context, " should be") : 'expected value is', " ").concat(error, " but received ").concat(value, "."), context); }; }; var restrict = function (caster, rules) { var validator = function (value, context, reportError) { if (reportError === void 0) { reportError = throw_type_error_1.throwTypeError; } var typedValue = caster(value, context, reportError); if (!(0, guards_1.isEmpty)(typedValue)) rules.forEach(applyRule(typedValue, context, reportError)); return typedValue; }; Reflect.defineProperty(validator, 'name', { value: caster.name }); return validator; }; exports.restrict = restrict;