Predicates
Set of various predicates for type checking, simple assertions, filtering etc.
Features
- written in typescript (with type guards and function overloading)
- well defined API design principles
- predicates description every predicate contains a proper description for easier debugging and automatic assertion generation
- supports simple type checks with unnecessary verbosity
- every predicate supports currying if possible
Install
npm install predicates
Full API
Example
const is = ; is; // falseis; // true is; // trueis; // trueis; // trueis; // trueisundefined; // trueis'timmy'; // true const isPerson = is; ; // true; // false, lack of name property
const assertName = is;const assertSurname = is;const assertAge = is; const Person = { ; ; ;} 'Tom' 'Welling' 33; // OK!'Tom' 'Welling'; // OK!'Tom' '' 33; // Error: Surname must be a string and cannot be emptye
API design
Generated predicates can be called with more than one argument
Most of type checking, utility libraries force you use predicates with only one argument but predicates doesn.t Additionally predicates preserves the context of function call which allows you to create even more powerful logic.
const is = ; const isOkToModifyTags = isall is { // no need to save them again if they are the same as previous ones return tags !== previousTags; }; Moduleprototype { var previousTags = ; if this; else // no need to save them again if they are the same as previous ones }
Prevents stupid mistakes (fail fast)
Predicates checks whether generated predicate is misconfigured and throws an error as fast as possible.
is; // Error: Prefix cannot be empty// since that would be true for all strings is; // Error: Collection cannot be empty// always false
That's why it's a good practice to create predicates at the beginning of a module definition to quickly catch any mistake.
// some moduleconst is = ;const isImage = is; // Error: Collection cannot be empty // You don't need to run the whole application to get the error that your predicate is wrong
Defined and generated predicates will never throw any error
You don't need to check the arguments provided to predicates to make sure they won't cause an error - predicates does it for you.
const isDuck = is; ; // false - no error; // false - no error; // false - no error is100; // false - no error
NOTE! This rule applies only for predicates defined in the library. Any user-defined predicate MAY throw errors (however I don't advise to do so) and predicates will not catch them.
const assertName = is.all(is.string, function(value) {
if (value === 'admin') {
throw new Error('Admin is a reserved user name');
}
});
assertName('admin'); // Error: Admin is a reserved user name
Type guards
Every predicate (if possible) is a type guard
if is.stringvalue
Core types are automatically translated to proper predicate
isfoo: 'bar'; // true // for less verbosity this is possible as wellisfoo: 'bar'; // trueis'foo'; // true