3.2.0 • Published 10 years ago
typd v3.2.0
typd
Runtime type-checking for JavaScript. Mostly a wrapper around typecheck.
Table of contents
Install
npm install --save typdUse
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.
API
Here are the available checkers:
Typd.anyTypd.noneTypd.booleanTypd.BooleanTypd.stringTypd.StringTypd.numberTypd.NumberTypd.ObjectTypd.functionmatches any function
There are others that accept other checkers as arguments to create compound checkers:
Typd.arrayOftakes another checker, and matches arrays that contain elements that pass the supplied checker type. For example,Typd.arrayOf(Typd.boolean)Typd.maybetakes another checker, matching that type or undefined. For example,Typd.maybe(Typd.boolean).Typd.oneOftakes many checkers and makes sure one of them matches. For example,Typd.oneOf(Typd.string, Typd.String).Typd.shapetakes 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)) })
Examples
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 => {/* ... */}
);Contributing
Please read the contribution guidelines. Contributions are welcome!
Thanks
Thanks to those who work on typecheck, without whom this would have been a lot more work.
License
Copyright (c) 2015 Tom Ashworth. Released under the MIT license.