ts-cast
Version:
Runtime typechecking
43 lines (42 loc) • 1.71 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.oneOf = exports.firstOf = exports.union = void 0;
var engine_1 = require("../engine");
var throw_type_error_1 = require("../engine/throw-type-error");
var names_1 = require("../helpers/names");
var checkTypes = function (casters, typeName) {
var unionCasterFn = function (value, context, reportError) {
if (reportError === void 0) { reportError = throw_type_error_1.throwTypeError; }
var match;
var errors = [];
var isMatched = casters.some(function (caster) {
try {
match = caster(value, context);
return true;
}
catch (err) {
errors.push("".concat(caster.name, ": ").concat(err.message));
return false;
}
});
if (isMatched)
return match;
return reportError("".concat(typeName, " is expected").concat(context ? " in ".concat(context) : '', " but no matching type was found:\n").concat(errors.map(function (e) { return " - ".concat(e); }).join('\n')), context);
};
return unionCasterFn;
};
var union = function () {
var casters = [];
for (var _i = 0; _i < arguments.length; _i++) {
casters[_i] = arguments[_i];
}
if (casters.length < 2) {
throw new Error('At least two types should be specified.');
}
var typeName = casters.map(function (c) { return c.name; }).join('|');
var casterFn = checkTypes(casters, typeName);
return (0, engine_1.casterApi)((0, names_1.withName)(casterFn, typeName));
};
exports.union = union;
exports.firstOf = exports.union;
exports.oneOf = exports.union;