1.0.1 • Published 9 years ago

typespec v1.0.1

Weekly downloads
4
License
-
Repository
github
Last release
9 years ago

TypeSpec

A library providing run-time type checking for JavaScript.

Installation

$ npm install typespec

Usage

TypeSpec works by comparing JavaScript expressions against type specifier strings.

The verification function handles both atomic and composite expressions. It also supports matching against wildcards, multiples, and key literals.

Note that, while useful in development, run-time type checking can be slow, and the author recommends eschewing it once software is ready to deploy. This library is intended to help eliminate bugs before deployment.

> var verifyType = require('TypeSpec').verify;
undefined

> verifyType("Number", 5);
true

> verifyType("(Number || String)", 5);
true

> verifyType("(Number || String)", "foo");
true

> verifyType("[Number, String]", [5, "foo"]);
true

> verifyType("[(Number || String), Number]", ["foo", 5]);
true

> verifyType("[*, *]", [1, function() {}]);
true

> verifyType("[Number ...]", [1, 2, 3, 4, 5]);
true

> verifyType("[*, Number ..., String]", ["foo", 1, 2, 3, "bar"]);
true

> verifyType("[[Number, Number] ...]", [[1, 2], [3, 4], [5, 6]]);
true

> verifyType("{*: String}", {foo: "bar"});
true

> verifyType("{*: String, *: Number}", {foo: "bar", num: 5});
true

> verifyType("{*: String ...}", {foo: "bar", bar: "foo", foobar: "barfoo"});
true

> verifyType("{$foo: String, $bar: Number}", {foo: "bar", bar: 5});
true

> verifyType("{*: [Number ...] ...}", {foo: [1, 2, 3], bar: [4, 5, 6]});
true

Under the Hood

TypeSpec was initially inspired by Common Lisp's check-type macro. It works by parsing type specifier strings into SExp-like structures, then comparing these against JavaScript expressions.

Release History

  • 1.0.0 Initial release

License

TypeSpec is provided as-is under the two-clause BSD license.