A modern type guard utility for Node.js
Installation
Requires Node.js v6 LTS or greater.
$ npm install vakt
Usage
Basic usage
vakt throws an error when a variable is not of the expected type.
const vakt = ; const greet = { vakt; return `Hello, !`;}; ; // => Hello, Alice! ; // => TypeError: name must be a string
vakt takes advantage of the ES6/ES2015 property value shorthand so you don't have to write the variable twice.
With Promises
You can also use vakt in Promises, since thrown errors automatically become rejections.
const vakt = ; const delay = { return { vakt; // if we reach this part, ms is guaranteed to be a number ; };}; ;// => 5 seconds have passed! ;// => TypeError: ms must be a number
Define custom types
vakt lets you create your own type checks by providing it with a validation function that returns true or false.
const vakt = ; vaktcustomTypes'non-negative integer' = vaktis && value >= 0; const pick = { vakt; vakt; return arrayindex;}; ; // => 16 ; // => TypeError: index must be a non-negative integer
Multiple checks at once
vakt also has a handy shorthand for checking multiple variables with one call.
const vakt = ; const doMaths = { vakt; let value = 1 / num1 * num2; if round value = Math; return value;}; ; // => 0.5 // => TypeError: round must be a boolean
API
vakt.check(variable, type)
vakt.check([[variable, type], [variable, type], [...]])
variable
Type: object
The variable to check. Should be in the form of { name: value }
.
Since you will practically always want to pass both the name and value of a variable,
you can make use of the ES6/ES2015 property value shorthand to save you some typing: { name }
type
Type: string
The type to validate against, passed as a string.
vakt.types
Type: array
An array containing the types vakt can check out of the box:
'array' 'boolean' 'date' 'decimal' 'function' 'integer' 'number' 'object' 'regexp' 'string'
vakt.is
Type: object
An instance of the is.js micro check library which vakt uses to perform type checks.
vakt.customTypes
Type: object
An object containing the custom types that have been added to vakt. To define a new custom type you can add a validation function directly to the object. The validation function should return true
or false
.
vaktcustomTypes'cat' = vaktisobjectvalue && vaktis;
Once you have defined a custom type, you can use it with vakt.check
:
const dog = { console; }; vakt; // => TypeError: dog must be a cat
vakt.VERSION
Type: string
The version of vakt in semver format.
License
MIT © Mick Dekkers