UNPKG

letype

Version:

Type checker for any data structures

1 lines 2.89 kB
var CustomType=function(){},Any=(function(t){function r(){t.apply(this,arguments)}t&&(r.__proto__=t);r.prototype=Object.create(t&&t.prototype);r.prototype.constructor=r;r.prototype.parse=function(){return!0};return r}(CustomType));function typeCheck(t,r,n,e){n===void 0&&(n=[]);e===void 0&&(e=!0);if(typeof r==='function'&&r.prototype instanceof CustomType){var o=new r,c=o.parse;if(typeof c==='function'){return c(t)}}var p=typeof r==='function'?r():r,u=typeof p,a=t!==void 0&&t!==null&&t.constructor===r;if(r===Date){return a}if(r&&r.constructor===RegExp&&p instanceof RegExp){var i=p.test(t);!i&&!e&&console.error(("Type error: Expected "+(n.length>0?"`"+(n.join('.'))+"`":'value')+" as `"+t+"` to pass regexp `"+p+"`"));return i}if(r===RegExp){return a}if(a){return!0}if(u==='object'&&typeof t==='object'){var l=!0;if(r&&r instanceof Function&&r.name==='Array'&&r.constructor instanceof Function){return(t&&t.constructor)===(r&&r.constructor)}if(r instanceof Array&&r.length===1){if(!(t&&t.length>-1)){return!1}for(var s in t){if({}.hasOwnProperty.call(t,s)){var y=typeCheck(t[s],r[0],n.concat(s),e);l&&(l=y)}}}else{var f=Object.assign({},r,t);for(var h in f){if({}.hasOwnProperty.call(f,h)){var g=typeCheck(f[h],r[h],n.concat(h),e);l&&(l=g)}}}return l}var _=typeof t===u;_||(t===void 0?(e||console.error(("Type error: "+(n.length>0?"`"+(n.join('.'))+"`":'Value')+" is undefined! Required value of type `"+u+"`"))):p===void 0?(e||console.error(("Type error: "+(n.length>0?"`"+(n.join('.'))+"`":'Value')+" is defined as `"+t+"`! But it should not be defined at all!"))):e||console.error(("Type error: `"+t+"` is not of type `"+u+"`"+(n.length>0?" in `"+(n.join('.'))+"`":''))));return _}function assert(t){var r=[],n=arguments.length-1;while(n-->0)r[n]=arguments[n+1];if(r&&r.length===1){if(!typeCheck(t,r[0],[],!0)){throw new TypeError('Type checker found some type mismatches!')}}else if(r&&r.length>1){var e=!1;r.forEach(function(r){return!e&&(e=typeCheck(t,r,[],!0))});if(!e){throw new TypeError(("`"+t+"` is not any of types: "+(r.map(function(t){return"`"+t.name+"`"}).join(', '))))}}return!0}function Or(){var t=[],r=arguments.length;while(r--)t[r]=arguments[r];var n=(function(r){function n(){r.apply(this,arguments)}r&&(n.__proto__=r);n.prototype=Object.create(r&&r.prototype);n.prototype.constructor=n;n.prototype.parse=function(r){return assert.apply(void 0,[r].concat(t))};return n}(CustomType));return n}var Undefined=(function(t){function r(){t.apply(this,arguments)}t&&(r.__proto__=t);r.prototype=Object.create(t&&t.prototype);r.prototype.constructor=r;r.prototype.parse=function(t){return typeof t==='undefined'};return r}(CustomType)),types={Any:Any,Or:Or,Custom:CustomType,Undefined:Undefined};function check(t){var r=[],n=arguments.length-1;while(n-->0)r[n]=arguments[n+1];try{assert.apply(void 0,[t].concat(r))}catch(t){return!1};return!0}export { assert, check, types }