|
|
||
|---|---|---|
| .. | ||
| src | ||
| COPYING | ||
| HISTORY.md | ||
| README.md | ||
| package.json | ||
README.md
check-types.js
A little JavaScript library for asserting types and values.
- Why would I want that?
- How little is it?
- How do I install it?
- How do I use it?
- Are there TypeScript definitions?
- Where can I use it?
- What changed from 7.x to 8.x?
- What changed from 6.x to 7.x?
- What changed from 5.x to 6.x?
- What changed from 4.x to 5.x?
- What changed from 3.x to 4.x?
- What changed from 2.x to 3.x?
- What changed from 1.x to 2.x?
- What changed from 0.x to 1.x?
- How do I set up the build environment?
- What license is it released under?
Why would I want that?
Writing explicit conditions in your functions to check arguments and throw exceptions is a task that swiftly becomes tiresome and adds complexity to your codebase.
The purpose of check-types.js is to remove this burden from JavaScript application developers in an efficient and robust manner, abstracted by a simple API.
How little is it?
20 kb unminified with comments, 5.7 kb minified, 2.1 kb minified + gzipped.
How do I install it?
Via npm:
npm i check-types --save
Or if you just want the git repo:
git clone git@gitlab.com:philbooth/check-types.js.git
If you're into other package managers, it is also available from Bower, Component and Jam.
How do I use it?
Loading the library
If you are running in
Node.js,
Browserify
or another CommonJS-style
environment,
you can require
check-types like so:
var check = require('check-types');
It also the supports the AMD-style format preferred by Require.js.
If you are
including check-types.js
with an HTML <script> tag,
or neither of the above environments
are detected,
it will export the interface globally as check.
Calling the exported functions
Once you've loaded the library in your application, a whole bunch of functions are available to call.
Most of the functions are predicates, which can be executed in a number of different contexts:
-
check.xxx(thing): These functions are basic predicates, returning true or false depending on the type and value ofthing. -
check.not.xxx(thing): Thenotmodifier negates predicates, returningtrueif the predicate returnsfalseandfalseif the predicate returnstrue. It is also itself a function, which simply returns the negation of its argument. -
check.maybe.xxx(thing): Themaybemodifier tweaks predicates to returntrueifthingisnullorundefined, otherwise their normal result is returned. It is also itself a function, which returnstruewhen its argument isnullorundefined, otherwise it returns its argument. -
check.assert.xxx(thing, message): Theassertmodifier changes predicates to throw when their result isfalse, otherwise it returnsthing. It can be applied to thenotandmaybemodifiers using the formscheck.assert.not.xxx(thing, message)andcheck.assert.maybe.xxx(thing, message). It is also itself a function, which simply throws when its argument is false. -
check.array.of.xxx(thing): Thearray.ofmodifier first checks that it is operating on an array and then applies the modified predicate to each item of the array. If the predicate fails for any item, it returnsfalse, otherwise it returnstrue. It can also be prefixed by other modifiers, socheck.maybe.array.of,check.not.array.of,check.assert.array.of,check.assert.maybe.array.ofandcheck.assert.not.array.ofall work as you would expect them to. -
check.arrayLike.of.xxx(thing): ThearrayLike.ofmodifier is synonymous witharray.of, except it operates on array-like objects. -
check.iterable.of.xxx(thing): Theiterable.ofmodifier is synonymous witharray.of, except it operates on iterables. -
check.object.of.xxx(thing): Theobject.ofmodifier is synonymous witharray.of, except it operates on an object's properties.
Additionally, there are some batch operations
to help you apply predicates
to each value
of an array or object.
These are implemented by
check.map,
check.any and
check.all.
General predicates
-
check.equal(thing, thang): Returnstrueifthing === thang,falseotherwise. -
check.null(thing): Returnstrueifthingisnull,falseotherwise. -
check.undefined(thing): Returnstrueifthingisundefined,falseotherwise. -
check.assigned(thing): Returnstrueifthingis notnullorundefined,falseotherwise. -
check.primitive(thing): Returnstrueifthingis a primitive type,falseotherwise. Primitive types arenull,undefined, booleans, numbers, strings and symbols. -
check.hasLength(thing, value): Returnstrueifthinghas a length property that equalsvalue,falseotherwise.
String predicates
-
check.string(thing): Returnstrueifthingis a string,falseotherwise. -
check.emptyString(thing): Returnstrueifthingis the empty string,falseotherwise. -
check.nonEmptyString(thing): Returnstrueifthingis a non-empty string,falseotherwise. -
check.contains(thing, substring): Returnstrueifthingis a string that containssubstring,falseotherwise. -
check.match(thing, regex): Returnstrueifthingis a string that matchesregex,falseotherwise.
Number predicates
-
check.number(thing): Returnstrueifthingis a number,falseotherwise. Note thatNaN,Number.POSITIVE_INFINITYandNumber.NEGATIVE_INFINITYare not considered numbers here. -
check.integer(thing): Returnstrueifthingis an integer,falseotherwise. -
check.zero(thing): Returnstrueifthingis zero,falseotherwise. -
check.infinity(thing): Returnstrueifthingis positive or negative infinity,falseotherwise. -
check.greater(thing, value): Returnstrueifthingis a number greater thanvalue,falseotherwise. -
check.greaterOrEqual(thing, value): Returnstrueifthingis a number greater than or equal tovalue,falseotherwise. -
check.less(thing, value): Returnstrueifthingis a number less thanvalue,falseotherwise. -
check.lessOrEqual(thing, value): Returnstrueifthingis a number less than or equal tovalue,falseotherwise. -
check.between(thing, a, b): Returnstrueifthingis a number betweenaandb(excludingaandb),falseotherwise. The argumentsaandbmay be in any order, it doesn't matter which is greater. -
check.inRange(thing, a, b): Returnstrueifthingis a number in the rangea..b(includingaandb),falseotherwise. The argumentsaandbmay be in any order, it doesn't matter which is greater. -
check.positive(thing): Returnstrueifthingis a number greater than zero,falseotherwise. -
check.negative(thing): Returnstrueifthingis a number less than zero,falseotherwise. -
check.odd(thing): Returnstrueifthingis an odd number,falseotherwise. -
check.even(thing): Returnstrueifthingis an even number,falseotherwise.
Boolean predicates
check.boolean(thing): Returnstrueifthingis a boolean,falseotherwise.
Object predicates
-
check.object(thing): Returnstrueifthingis a plain-old JavaScript object,falseotherwise. -
check.emptyObject(thing): Returnstrueifthingis an empty object,falseotherwise. -
check.nonEmptyObject(thing): Returnstrueifthingis a non-empty object,falseotherwise. -
check.instanceStrict(thing, prototype): Returnstrueifthingis an instance ofprototype,falseotherwise. -
check.instance(thing, prototype): Returnstrueifthingis an instance ofprototype,falseotherwise. Falls back to testingconstructor.nameandObject.prototype.toStringif theinstanceoftest fails. -
check.like(thing, duck): Duck-typing checker. Returnstrueifthinghas all of the properties ofduck,falseotherwise.
Array predicates
-
check.array(thing): Returnstrueifthingis an array,falseotherwise. -
check.emptyArray(thing): Returnstrueifthingis an empty array,falseotherwise. -
check.nonEmptyArray(thing): Returnstrueifthingis a non-empty array,falseotherwise. -
check.arrayLike(thing): Returnstrueifthinghas a numeric length property,falseotherwise. -
check.iterable(thing): Returnstrueifthingimplements the iterable protocol,falseotherwise. In pre-ES6 environments, this predicate falls back toarrayLikebehaviour. -
check.includes(thing, value): Returnstrueifthingincludesvalue,falseotherwise.
Date predicates
check.date(thing): Returnstrueifthingis a valid date,falseotherwise.
Function predicates
check.function(thing): Returnstrueifthingis a function,falseotherwise.
Modifiers
-
check.not(value): Returns the negation ofvalue. -
check.not.xxx(...): Returns the negation of the predicate. -
check.maybe(value): Returnstrueifvalueisnullorundefined, otherwise it returnsvalue. -
check.maybe.xxx(...): Returnstrueifthingisnullorundefined, otherwise it propagates the return value from its predicate. -
check.array.of.xxx(value): Returnstrueifvalueis an array and the predicate is true for every item. Also works with thenotandmaybemodifiers. -
check.arrayLike.of.xxx(thing): ThearrayLike.ofmodifier is synonymous witharray.of, except it operates on array-like objects. -
check.iterable.of.xxx(thing): Theiterable.ofmodifier is synonymous witharray.of, except it operates on iterables. -
check.object.of.xxx(thing): Theobject.ofmodifier is synonymous witharray.of, except it operates on an object's properties. -
check.assert(value, message, ErrorType): Throws aTypeErrorifvalueis falsy, otherwise it returnsvalue.messageandErrorTypeare optional arguments that control the message and type of the thrown error object. -
check.assert.xxx(...): Throws aTypeErrorif the predicate returns false, otherwise it returns the subject value. The last two arguments are an optional message and error type that control the message and type of the thrown error object. Also works with thenot,maybeand...ofmodifiers.
Batch operations
-
check.map(things, predicates): Maps each value from thethingsarray or object to the corresponding predicate and returns the array or object of results. Passing a single predicate instead of an array or object maps all of the values to the same predicate. -
check.all(results): Returnstrueif all the result values are true in an array or object returned bymap. -
check.any(results): Returnstrueif any result value is true in an array or object returned bymap.
Some examples
check.even(3);
// Returns false
check.not.even(3);
// Returns true
check.maybe.even(null);
// Returns true
check.assert.like({ foo: 'bar' }, { baz: 'qux' });
// Throws `new TypeError('Invalid type')`
check.assert.not.like({ foo: 'bar' }, { baz: 'qux' });
// Doesn't throw, returns `{ foo: 'bar' }`
check.assert.maybe.like(undefined, { foo: 'bar' });
// Doesn't throw, returns `undefined`
check.assert(myFunction(), 'Something went wrong', CustomError);
// Throws `new CustomError('Something went wrong')` if myFunction returns `false`
check.map([ 'foo', 'bar', '' ], check.nonEmptyString);
// Returns [ true, true, false ]
check.map({
foo: 2,
bar: { baz: 'qux' }
}, {
foo: check.odd,
bar: { baz: check.nonEmptyString }
});
// Returns { foo: false, bar: { baz: true } }
check.all(
check.map(
{ foo: 0, bar: '' },
{ foo: check.number, bar: check.string }
)
);
// Returns true
check.any(
check.map(
[ 1, 2, 3, '' ],
check.string
)
);
// Returns true
Are there TypeScript definitions?
Yes!
Thanks to @idchlife, type definitions were added to DefinitelyTyped. You can add them to your project via npm:
npm i @types/check-types --save-dev
Where can I use it?
As of version 2.0, this library no longer supports ES3. That means you can't use it in IE 7 or 8.
Everywhere else should be fine.
If those versions of IE are important to you, worry not! The 1.x versions all support old IE and any future 1.x versions will adhere to that too.
See the releases for more information.
What changed from 7.x to 8.x?
Breaking changes were made to the API in version 8.0.0.
Specifically,
the apply batch operation was removed
and map was instead changed
to work with both arrays and objects,
to simplify the API surface.
See the history for more details.
What changed from 6.x to 7.x?
Breaking changes were made to the API in version 7.0.0.
Specifically,
the instance predicate
was renamed to instanceStrict
and the builtIn and userDefined predicates
were combined to form
a new instance predicate.
See the history for more details.
What changed from 5.x to 6.x?
Breaking changes were made to the API in version 6.0.0.
Specifically,
the either modifier was removed.
Instead,
calling code can use
the any function,
or simply express the boolean logic
in JS.
See the history for more details.
What changed from 4.x to 5.x?
Breaking changes were made to the API in version 5.0.0.
Specifically,
the predicates isMap and error were removed
in favour of the new predicate builtIn,
which can be used to test for
all built-in objects.
See the history for more details.
What changed from 3.x to 4.x?
Breaking changes were made to the API in version 4.0.0.
Specifically,
the predicate unemptyString
was renamed to nonEmptyString
and the predicate error
was changed to support
derived Error objects.
See the history for more details.
What changed from 2.x to 3.x?
Breaking changes were made to the API in version 3.0.0.
Specifically,
the predicate length
was renamed to hasLength
and the predicate webUrl
was removed.
See the history for more details.
What changed from 1.x to 2.x?
Breaking changes were made to the API in version 2.0.0.
Specifically:
- Support for ES3 was dropped
- The predicates
gitUrl,emailandfloatNumberwere removed. verifywas renamed toassert.nulledwas renamed tonull.oddNumberwas renamed toodd.evenNumberwas renamed toeven.positiveNumberwas renamed topositive.negativeNumberwas renamed tonegative.intNumberwas renamed tointeger.boolwas renamed toboolean.definedwas swapped to becomeundefined.webUrlwas tightened to reject more cases.
See the history for more details.
What changed from 0.x to 1.x?
Breaking changes were made to the API in version 1.0.0.
Specifically,
all of the predicates
were renamed
from check.isXxxx
to check.xxx and
all of the verifiers
were renamed
from check.verifyXxxx
to check.verify.xxx.
See the history for more details.
How do I set up the build environment?
The build environment relies on
Node.js,
NPM,
JSHint,
Mocha,
Chai,
UglifyJS and
please-release-me.
Assuming that you already have Node.js and NPM set up,
you just need to run npm install to
install all of the dependencies as listed in package.json.
The unit tests are in test/check-types.js.
You can run them with the command npm test.
To run the tests in a web browser,
open test/check-types.html.