A little JavaScript library for asserting types and values, with zero dependencies.
This repository was forked from check-types.js after the original project was archived. Thanks a lot to Phil Booth for the original work!
- 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 10.x to 11.x?
- What changed from 9.x to 10.x?
- What changed from 8.x to 9.x?
- 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?
Writing explicit conditions in your functions to check arguments and throw errors is a task that swiftly becomes tiresome and adds complexity to your codebase.
The purpose of check-types-2 is to remove this burden from JavaScript application developers in an efficient and robust manner, abstracted by a simple API.
24 kb unminified with comments, 7.1 kb minified, 2.5 kb minified + gzipped.
Via npm:
npm i check-types-2 --save
Or if you just want the git repo:
git clone git@github.com:stheine/check-types-2.git
If you are running in Node.js
or a CommonJS environment,
you can require
check-types like so:
const check = require('check-types-2');
It also the supports the AMD-style format preferred by Require.js.
If you are
including check-types-2
with an HTML <script>
tag,
or neither of the above environments
are detected,
it will export the interface globally as check
.
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)
: Thenot
modifier negates predicates, returningtrue
if the predicate returnsfalse
andfalse
if the predicate returnstrue
. It is also itself a function, which simply returns the negation of its argument. -
check.maybe.xxx(thing)
: Themaybe
modifier tweaks predicates to returntrue
ifthing
isnull
orundefined
, otherwise their normal result is returned. It is also itself a function, which returnstrue
when its argument isnull
orundefined
, otherwise it returns its argument. -
check.assert.xxx(thing, message)
: Theassert
modifier changes predicates to throw when their result isfalse
, otherwise it returnsthing
. It can be applied to thenot
andmaybe
modifiers 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.of
modifier 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.of
andcheck.assert.not.array.of
all work as you would expect them to. -
check.arrayLike.of.xxx(thing)
: ThearrayLike.of
modifier is synonymous witharray.of
, except it operates on array-like objects. -
check.iterable.of.xxx(thing)
: Theiterable.of
modifier is synonymous witharray.of
, except it operates on iterables. -
check.object.of.xxx(thing)
: Theobject.of
modifier 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
.
-
check.equal(thing, thang)
: Returnstrue
ifthing === thang
,false
otherwise. -
check.null(thing)
: Returnstrue
ifthing
isnull
,false
otherwise. -
check.undefined(thing)
: Returnstrue
ifthing
isundefined
,false
otherwise. -
check.assigned(thing)
: Returnstrue
ifthing
is notnull
orundefined
,false
otherwise. -
check.primitive(thing)
: Returnstrue
ifthing
is a primitive type,false
otherwise. Primitive types arenull
,undefined
, booleans, numbers, strings and symbols. -
check.hasLength(thing, value)
: Returnstrue
ifthing
has a length property that equalsvalue
,false
otherwise.
-
check.string(thing)
: Returnstrue
ifthing
is a string,false
otherwise. -
check.emptyString(thing, options)
: Returnstrue
ifthing
is the empty string,false
otherwise. -
check.nonEmptyString(thing, options)
: Returnstrue
ifthing
is a non-empty string,false
otherwise. -
check.contains(string, substring)
: Returnstrue
ifstring
containssubstring
,false
otherwise. -
check.in(substring, string)
: Returnstrue
ifsubstring
is instring
,false
otherwise. -
check.match(string, regex)
: Returnstrue
ifstring
matchesregex
,false
otherwise.
-
check.number(thing)
: Returnstrue
ifthing
is a number,false
otherwise. Note thatNaN
,Number.POSITIVE_INFINITY
andNumber.NEGATIVE_INFINITY
are not considered numbers here. -
check.integer(thing)
: Returnstrue
ifthing
is an integer,false
otherwise. -
check.float(thing)
: Returnstrue
ifthing
is a non-integer number,false
otherwise. -
check.zero(thing)
: Returnstrue
ifthing
is zero,false
otherwise. -
check.one(thing)
: Returnstrue
ifthing
is one,false
otherwise. -
check.infinity(thing)
: Returnstrue
ifthing
is positive or negative infinity,false
otherwise. -
check.greater(thing, value)
: Returnstrue
ifthing
is a number greater thanvalue
,false
otherwise. -
check.greaterOrEqual(thing, value)
: Returnstrue
ifthing
is a number greater than or equal tovalue
,false
otherwise. -
check.less(thing, value)
: Returnstrue
ifthing
is a number less thanvalue
,false
otherwise. -
check.lessOrEqual(thing, value)
: Returnstrue
ifthing
is a number less than or equal tovalue
,false
otherwise. -
check.between(thing, a, b)
: Returnstrue
ifthing
is a number betweena
andb
(excludinga
andb
),false
otherwise. The argumentsa
andb
may be in any order, it doesn't matter which is greater. -
check.inRange(thing, a, b)
: Returnstrue
ifthing
is a number in the rangea
..b
(includinga
andb
),false
otherwise. The argumentsa
andb
may be in any order, it doesn't matter which is greater. -
check.positive(thing)
: Returnstrue
ifthing
is a number greater than zero,false
otherwise. -
check.negative(thing)
: Returnstrue
ifthing
is a number less than zero,false
otherwise. -
check.odd(thing)
: Returnstrue
ifthing
is an odd number,false
otherwise. -
check.even(thing)
: Returnstrue
ifthing
is an even number,false
otherwise.
-
check.boolean(thing)
: Returnstrue
ifthing
is a boolean,false
otherwise. -
check.true(thing)
: Returnstrue
ifthing
is true,false
otherwise. -
check.false(thing)
: Returnstrue
ifthing
is false,false
otherwise.
-
check.object(thing)
: Returnstrue
ifthing
is a plain-old JavaScript object,false
otherwise. -
check.emptyObject(thing)
: Returnstrue
ifthing
is an empty object,false
otherwise. -
check.nonEmptyObject(thing)
: Returnstrue
ifthing
is a non-empty object,false
otherwise. -
check.thenable(thing)
: Returnstrue
ifthing
has athen
method,false
otherwise. -
check.instanceStrict(thing, prototype)
: Returnstrue
ifthing
is an instance ofprototype
,false
otherwise. -
check.instance(thing, prototype)
: Returnstrue
ifthing
is an instance ofprototype
,false
otherwise. Falls back to testingconstructor.name
andObject.prototype.toString
if theinstanceof
test fails. -
check.contains(object, value)
: Returnstrue
ifobject
containsvalue
,false
otherwise. -
check.in(value, object)
: Returnstrue
ifvalue
is inobject
,false
otherwise. -
check.containsKey(object, key)
: Returnstrue
ifobject
contains keykey
,false
otherwise. -
check.keyIn(key, object)
: Returnstrue
if keykey
is inobject
,false
otherwise. -
check.like(thing, duck)
: Duck-typing checker. Returnstrue
ifthing
has all of the properties ofduck
,false
otherwise. -
check.identical(thing, thang)
: Deep equality checker. Returnstrue
ifthing
has all of the same values asthang
,false
otherwise.
-
check.array(thing)
: Returnstrue
ifthing
is an array,false
otherwise. -
check.emptyArray(thing)
: Returnstrue
ifthing
is an empty array,false
otherwise. -
check.nonEmptyArray(thing)
: Returnstrue
ifthing
is a non-empty array,false
otherwise. -
check.arrayLike(thing)
: Returnstrue
ifthing
has a numeric length property,false
otherwise. -
check.iterable(thing)
: Returnstrue
ifthing
implements the iterable protocol,false
otherwise. In pre-ES6 environments, this predicate falls back toarrayLike
behaviour. -
check.contains(array, value)
: Returnstrue
ifarray
containsvalue
,false
otherwise. -
check.in(value, array)
: Returnstrue
ifvalue
is inarray
,false
otherwise.
check.date(thing)
: Returnstrue
ifthing
is a valid date,false
otherwise.
-
check.function(thing)
: Returnstrue
ifthing
is a function,false
otherwise. -
check.throws(() => thing())
: Returnstrue
ifthing
is a function that throws,false
otherwise. -
check.throwsWith(() => thing(), message)
: Returnstrue
ifthing
is a function that throws with a specific error,false
otherwise.message
can be a string or pattern. -
await check.rejects(async() => await thing(), message)
: Returnstrue
ifthing
as an async function / function returning a Promise that is rejecting with a specific error,false
otherwise.message
can be a string or pattern. -
await check.rejectsWith(async() => await thing(), message)
: Returnstrue
ifthing
as an async function / function returning a Promise that is rejecting with a specific error,false
otherwise.message
can be a string or pattern.
-
check.not(value)
: Returns the negation ofvalue
. -
check.not.xxx(...)
: Returns the negation of the predicate. -
check.maybe(value)
: Returnstrue
ifvalue
isnull
orundefined
, otherwise it returnsvalue
. -
check.maybe.xxx(...)
: Returnstrue
ifthing
isnull
orundefined
, otherwise it propagates the return value from its predicate. -
check.array.of.xxx(value)
: Returnstrue
ifvalue
is an array and the predicate is true for every item. Also works with thenot
andmaybe
modifiers. -
check.arrayLike.of.xxx(thing)
: ThearrayLike.of
modifier is synonymous witharray.of
, except it operates on array-like objects. -
check.iterable.of.xxx(thing)
: Theiterable.of
modifier is synonymous witharray.of
, except it operates on iterables. -
check.object.of.xxx(thing)
: Theobject.of
modifier is synonymous witharray.of
, except it operates on an object's properties. -
check.assert(value, message, ErrorType)
: Throws aTypeError
ifvalue
is falsy, otherwise it returnsvalue
.message
andErrorType
are optional arguments that control the message and type of the thrown error object. -
check.assert.xxx(...)
: Throws aTypeError
if 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
,maybe
and...of
modifiers.
-
check.map(things, predicates)
: Maps each value from thethings
array 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)
: Returnstrue
if all the result values are true in an array or object returned bymap
. -
check.any(results)
: Returnstrue
if any result value is true in an array or object returned bymap
.
check.even(3);
// Returns false
check.not.even(3);
// Returns true
check.maybe.even(null);
// Returns true
check.assert.even(3);
// Throws `new TypeError('assert failed: expected 3 to be even number')`
check.assert.not.even(3);
// Doesn't throw
check.assert.maybe.even(null);
// Doesn't throw
check.contains('foo', 'oo')
// Returns true
check.contains('foe', 'oo')
// Returns false
check.contains(['foo', 'bar'], 'bar')
// Returns true
check.contains(['foo', 'bar'], 'ar')
// Returns false
check.like({ foo: 'bar' }, { foo: 'baz' });
// Returns true
check.like({ foo: 'bar' }, { baz: 'qux' });
// Returns false
check.array.of.nonEmptyString([ 'foo', 'bar' ]);
// Returns true
check.array.of.nonEmptyString([ 'foo', 'bar', '' ]);
// Returns false
check.array.of.inRange([ 0, 1, 2 ], 0, 2);
// Returns true
check.array.of.inRange([ 0, 1, 2 ], 0, 1);
// Returns false
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
check.throws(() => {
testFunction({called: 'with wrong parameters'}); // Throws on wrong parameters
});
// Returns true
check.throwsWith(() => {
testFunction({called: 'with wrong parameters'}); // Throws 'wrong parameters'
}, 'wrong parameters');
// Returns true
check.throwsWith(() => {
testFunction({called: 'with wrong parameters'}); // Throws 'wrong parameters'
}, /parameter$/);
// Returns true
await check.rejects(async() => {
await testFunction({called: 'with wrong parameters'}); // Throws on wrong parameters
});
// Returns true
await check.rejectsWith(async() => {
await testFunction({called: 'with wrong parameters'}); // Throws 'wrong parameters'
}, 'wrong parameters');
// Returns true
await check.rejectsWith(async() => {
await testFunction({called: 'with wrong parameters'}); // Throws 'wrong parameters'
}, /parameters$/);
// Returns true
No
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.
Breaking changes were made to the API in version 11.0.0.
Specifically,
the options
argument was removed
from the emptyString
and nonEmptyString
predicates
because it caused problematic behaviour in the assert
modifier.
Callers who were previously using options.trim
with these predicates
should call check.match
instead:
check.match(stringWithSpaces, /^\s*$/);
See the history for more details.
Breaking changes were made to the API in version 10.0.0.
Specifically,
the includes
predicate
was merged into the contains
predicate
and errors thrown by the assert
modifier
were given more useful error messages
including details about the failing data.
See the history for more details.
Breaking changes were made to the API in version 9.0.0.
Specifically,
an options
argument was added
to the emptyString
and nonEmptyString
predicates.
In each case,
if options.trim
is truthy,
strings will be trimmed
before making the comparison.
See the history for more details.
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.
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.
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.
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.
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.
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.
Breaking changes were made to the API in version 2.0.0.
Specifically:
- Support for ES3 was dropped
- The predicates
gitUrl
,email
andfloatNumber
were removed. verify
was renamed toassert
.nulled
was renamed tonull
.oddNumber
was renamed toodd
.evenNumber
was renamed toeven
.positiveNumber
was renamed topositive
.negativeNumber
was renamed tonegative
.intNumber
was renamed tointeger
.bool
was renamed toboolean
.defined
was swapped to becomeundefined
.webUrl
was tightened to reject more cases.
See the history for more details.
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.
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-2
.
You can run them with the command npm test
.
To run the tests in a web browser,
open test/check-types-2.html
.