Ensure.js
A simple library for checking types in Javascript + extras
Changes
0.5.3
- Fix bug that would not allow ensure.shield() with Nullable in the function arguments, due to the argument number length
0.5.2
- Added ensure.one()
0.5.1
- Nullable types: It is now possible to type check a type or a null value
- Nothing type (alias of undefined): You can now type check
undefined
, which is mostly useless. However, on function shields, Nothing is used to specify when a function doesn't return a value - 100% test coverage
0.5.0
- Shield (Beta): Protect functions by adding a wrapper that checks function parameters and return values
- Documentation (Online Version)
- Enforcenment is now optional with
ensure.enforce
. Production code can skip type checks and run faster. - [Breaking] has() no longer throws exceptions by default, it behaves like ensure() now with a
soft
parameter
Usage
Ensure is available as a global variable (or a module on Node):
ensure(object, type, soft = false)
- object: Is the object you are checking
- type: Is the type you are expecting It can be any "class" in JavaScript, such as
String
,Error
, orBoolean
. - soft: If set to true, ensure won't throw an error when the type does not match
For most objects, Ensure will do a simple instanceof
check. However, some built-in objects (String, Number, Boolean)
are trickier to check so the library will do some custom checking functions for these.
To check if a variable is a string:
var hello = 'Hello World'; ;>> true var notString = 1337; ;>> false
The previous example is using the "soft mode", which means that ensure won't throw an Error when a type does not match, instead it will return a boolean value.
On the default mode:
var hello = 'Hello World'; ;>> undefined ;>> TypeException: Invalid type: Expected String
On the browser
1.- Install using Bower:
bower install ensure.js
2.- Include the JS file on your project:
3.- Use it!
console;
On Node.js
1.- Install using npm:
npm install ensure.js
2.- Include the library in your project:
var ensure = ;
3.- Use it!
console;
Supported types:
- String
- Number
- Boolean
- Array
- (Any object)
Record Types
Languages like C++, Hack and Haskell have nice syntax for data types that hold information. You might know them as Structs or Records. Ensure.js provides an emulation of this format. I say emulation because it is not analyzed statically and might have some behavior differences. However, it can be useful for adding some validation to certain objects in your application. Instead of blindly assuming that a certain variable of an object is of a certain type you can use Ensure Records which automatically perform these checks for you.
Please note that if performance is important, it is always faster to just use regular objects.
EnsureRecord(spec)
spec: The spec is an object specifying the types of each variable in the record, where the key is the name of the property and the value the type to expect.
EnsureRecordType(values)
values: The values being applied to the instance being instantiated. Will throw an error if the types do not match the spec
Example:
var ensure = EnsureRecord = ensureEnsureRecord; // First, we create our person typevar Person = firstName: String lastName: String age: Number ; // Then we create an instance by providing its valuesvar bob = firstName: "Bob" lastName: "Lulz" age: 20 ; console>>> "Bob" // Note that if we try to brake the spec, we get an errorvar alex = firstName: "Bob" lastName: "Lulz" age: "Old" ;>>> TypeException // Same with setters:bobname = 1 5 7;>>> TypeException
Shields
Version 0.5.0 now comes with a factory function called Shield (ensure.shield), which allows you to add a simple wrapper around your function that will type check your arguments and your return values automatically for you:
// First we create our shielded functionvar myShieldFunction = ensure; // This works fine; // This throws an error; // This also throws an error since the return value is not a number;
Nothing
Sometimes shielded functions do not return a value, in these cases we use Nothing
which is an alias for undefined
:
var Nothing = ensureNothing myVal myShieldFunction; myShieldFunction = ensure;
Nullable
Nullable allows the type check input to be null
or the type we are expecting:
var Nullable = ensureNullable; // We can also allow a variable to be null;>> true ;>> false
You can also use NullableInstances in your code:
var Nullable = ensureNullable NullableInstance = ensureNullableInstance SomeNullableArray = Array ; // Check if it is nullSomeNullableArray;>> false // This works fineSomeNullableArray; // Check if it is null againSomeNullableArray;>> true // They can also be type checked;>> true // This does notSomeNullableArray;
Other Extras:
require(object)
Throw an error if object
is undefined, null or an empty string:
var hello; ensure;>> Error hello = ''; ensure;>> Error hello = 'Hello World'; ensure; // This shouldn't do anything (which is good)>> undefined
requireIsNewThis(constructor, context)
Throw an error if a constructor is called without new
Useful for preventing development mistakes
var { ensure;}; var instance = ; // This should just create the instance normally>> undefined var instance = ; // An error is thrown, new is missing>> Error
isIn(object, array) Check if object is in an array:
ensure;
isInRange(object, min, max) Check if a number is within a range:
ensure;
Example:
var hello = 'Hello'; ensure;>> false ensure;>> true
isPositiveNumber(object) Check if a number is positive:
ensure;
and a few more, take a look at the docs
Development
To hack on Ensure.js, you need Node.js 0.10+. To setup a dev environment, run the following:
1.- Install grunt:
npm install -g grunt
2.- Clone repo:
git clone git@github.com:eduard44/ensure.git
3.- cd to repo:
cd ensure
4.- Install dependencies for development:
npm install
(in the project root)
5.- Start grunt in watch mode:
grunt
. This will continuously rebuild ensure.js on every change in /src
6.- You can run tests with:
npm test
7.- You can check code coverage with:
grunt coverage
8.- You can compile documentation with:
grunt jsdoc