Runtime type-checking for JavaScript. Mostly a wrapper around typecheck.
npm install --save typd
typd
wraps functions to add runtime type-checks to them. The resulting function will throw if the arguments don't match.
import Typd from 'typd';
const add =
Typd(
['a', Typd.number],
['b', Typd.number],
(a, b) => a + b
);
The Typd
function takes any number of [string, function]
tuples that represent argument name and the checker, and finally the function to be wrapped.
Here are the available checkers:
Typd.any
Typd.none
Typd.boolean
Typd.Boolean
Typd.string
Typd.String
Typd.number
Typd.Number
Typd.Object
Typd.function
matches any function
There are others that accept other checkers as arguments to create compound checkers:
Typd.arrayOf
takes another checker, and matches arrays that contain elements that pass the supplied checker type. For example,Typd.arrayOf(Typd.boolean)
Typd.maybe
takes another checker, matching that type or undefined. For example,Typd.maybe(Typd.boolean)
.Typd.oneOf
takes many checkers and makes sure one of them matches. For example,Typd.oneOf(Typd.string, Typd.String)
.Typd.shape
takes an object that describes the expected shape of the value. The values should be (any) other checkers. For example,Typd.shape({ a: Typd.number, b: Typd.maybe(Typd.arrayOf(Typd.string)) })
const { maybe, arrayOf, oneOf, string, number, shape } = Typd;
// Match two numbers and an optional options object
var f = Typd(
['a', number],
['b', number],
['opts', maybe(Typd.Object)],
(a, b, opts={}) => {/* ... */}
);
// Match an optional array of either strings or numbers.
var f = Typd(
['args', maybe(arrayOf(oneOf(string, number)))],
(args) => {/* ... */}
);
// Match a string and an optional callback function
var f = Typd(
['path', string],
['cb', maybe(Typd.function)],
(path, cb) => {/* ... */}
);
// Match a user object
var f = Typd(
['user', Typd.shape({
id: Typd.string,
username: Typd.string,
followers: Typd.number,
contact: Typd.shape({
emails: Typd.arrayOf(Typd.string),
phones: Typd.arrayOf(Typd.string)
})
})],
user => {/* ... */}
);
Please read the contribution guidelines. Contributions are welcome!
Thanks to those who work on typecheck, without whom this would have been a lot more work.
Copyright (c) 2015 Tom Ashworth. Released under the MIT license.