1 | # type-check [![Build Status](https://travis-ci.org/gkz/type-check.png?branch=master)](https://travis-ci.org/gkz/type-check)
|
2 |
|
3 | <a name="type-check" />
|
4 |
|
5 | `type-check` is a library which allows you to check the types of JavaScript values at runtime with a Haskell like type syntax. It is great for checking external input, for testing, or even for adding a bit of safety to your internal code. It is a major component of [levn](https://github.com/gkz/levn). MIT license. Version 0.4.0. Check out the [demo](http://gkz.github.io/type-check/).
|
6 |
|
7 | For updates on `type-check`, [follow me on twitter](https://twitter.com/gkzahariev).
|
8 |
|
9 | npm install type-check
|
10 |
|
11 | ## Quick Examples
|
12 |
|
13 | ```js
|
14 | // Basic types:
|
15 | var typeCheck = require('type-check').typeCheck;
|
16 | typeCheck('Number', 1); // true
|
17 | typeCheck('Number', 'str'); // false
|
18 | typeCheck('Error', new Error); // true
|
19 | typeCheck('Undefined', undefined); // true
|
20 |
|
21 | // Comment
|
22 | typeCheck('count::Number', 1); // true
|
23 |
|
24 | // One type OR another type:
|
25 | typeCheck('Number | String', 2); // true
|
26 | typeCheck('Number | String', 'str'); // true
|
27 |
|
28 | // Wildcard, matches all types:
|
29 | typeCheck('*', 2) // true
|
30 |
|
31 | // Array, all elements of a single type:
|
32 | typeCheck('[Number]', [1, 2, 3]); // true
|
33 | typeCheck('[Number]', [1, 'str', 3]); // false
|
34 |
|
35 | // Tuples, or fixed length arrays with elements of different types:
|
36 | typeCheck('(String, Number)', ['str', 2]); // true
|
37 | typeCheck('(String, Number)', ['str']); // false
|
38 | typeCheck('(String, Number)', ['str', 2, 5]); // false
|
39 |
|
40 | // Object properties:
|
41 | typeCheck('{x: Number, y: Boolean}', {x: 2, y: false}); // true
|
42 | typeCheck('{x: Number, y: Boolean}', {x: 2}); // false
|
43 | typeCheck('{x: Number, y: Maybe Boolean}', {x: 2}); // true
|
44 | typeCheck('{x: Number, y: Boolean}', {x: 2, y: false, z: 3}); // false
|
45 | typeCheck('{x: Number, y: Boolean, ...}', {x: 2, y: false, z: 3}); // true
|
46 |
|
47 | // A particular type AND object properties:
|
48 | typeCheck('RegExp{source: String, ...}', /re/i); // true
|
49 | typeCheck('RegExp{source: String, ...}', {source: 're'}); // false
|
50 |
|
51 | // Custom types:
|
52 | var opt = {customTypes:
|
53 | {Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; }}}};
|
54 | typeCheck('Even', 2, opt); // true
|
55 |
|
56 | // Nested:
|
57 | var type = '{a: (String, [Number], {y: Array, ...}), b: Error{message: String, ...}}'
|
58 | typeCheck(type, {a: ['hi', [1, 2, 3], {y: [1, 'ms']}], b: new Error('oh no')}); // true
|
59 | ```
|
60 |
|
61 | Check out the [type syntax format](#syntax) and [guide](#guide).
|
62 |
|
63 | ## Usage
|
64 |
|
65 | `require('type-check');` returns an object that exposes four properties. `VERSION` is the current version of the library as a string. `typeCheck`, `parseType`, and `parsedTypeCheck` are functions.
|
66 |
|
67 | ```js
|
68 | // typeCheck(type, input, options);
|
69 | typeCheck('Number', 2); // true
|
70 |
|
71 | // parseType(type);
|
72 | var parsedType = parseType('Number'); // object
|
73 |
|
74 | // parsedTypeCheck(parsedType, input, options);
|
75 | parsedTypeCheck(parsedType, 2); // true
|
76 | ```
|
77 |
|
78 | ### typeCheck(type, input, options)
|
79 |
|
80 | `typeCheck` checks a JavaScript value `input` against `type` written in the [type format](#type-format) (and taking account the optional `options`) and returns whether the `input` matches the `type`.
|
81 |
|
82 | ##### arguments
|
83 | * type - `String` - the type written in the [type format](#type-format) which to check against
|
84 | * input - `*` - any JavaScript value, which is to be checked against the type
|
85 | * options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types)
|
86 |
|
87 | ##### returns
|
88 | `Boolean` - whether the input matches the type
|
89 |
|
90 | ##### example
|
91 | ```js
|
92 | typeCheck('Number', 2); // true
|
93 | ```
|
94 |
|
95 | ### parseType(type)
|
96 |
|
97 | `parseType` parses string `type` written in the [type format](#type-format) into an object representing the parsed type.
|
98 |
|
99 | ##### arguments
|
100 | * type - `String` - the type written in the [type format](#type-format) which to parse
|
101 |
|
102 | ##### returns
|
103 | `Object` - an object in the parsed type format representing the parsed type
|
104 |
|
105 | ##### example
|
106 | ```js
|
107 | parseType('Number'); // [{type: 'Number'}]
|
108 | ```
|
109 | ### parsedTypeCheck(parsedType, input, options)
|
110 |
|
111 | `parsedTypeCheck` checks a JavaScript value `input` against parsed `type` in the parsed type format (and taking account the optional `options`) and returns whether the `input` matches the `type`. Use this in conjunction with `parseType` if you are going to use a type more than once.
|
112 |
|
113 | ##### arguments
|
114 | * type - `Object` - the type in the parsed type format which to check against
|
115 | * input - `*` - any JavaScript value, which is to be checked against the type
|
116 | * options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types)
|
117 |
|
118 | ##### returns
|
119 | `Boolean` - whether the input matches the type
|
120 |
|
121 | ##### example
|
122 | ```js
|
123 | parsedTypeCheck([{type: 'Number'}], 2); // true
|
124 | var parsedType = parseType('String');
|
125 | parsedTypeCheck(parsedType, 'str'); // true
|
126 | ```
|
127 |
|
128 | <a name="type-format" />
|
129 | ## Type Format
|
130 |
|
131 | ### Syntax
|
132 |
|
133 | White space is ignored. The root node is a __Types__.
|
134 |
|
135 | * __Identifier__ = `[\$\w]+` - a group of any lower or upper case letters, numbers, underscores, or dollar signs - eg. `String`
|
136 | * __Type__ = an `Identifier`, an `Identifier` followed by a `Structure`, just a `Structure`, or a wildcard `*` - eg. `String`, `Object{x: Number}`, `{x: Number}`, `Array{0: String, 1: Boolean, length: Number}`, `*`
|
137 | * __Types__ = optionally a comment (an `Identifier` followed by a `::`), optionally the identifier `Maybe`, one or more `Type`, separated by `|` - eg. `Number`, `String | Date`, `Maybe Number`, `Maybe Boolean | String`
|
138 | * __Structure__ = `Fields`, or a `Tuple`, or an `Array` - eg. `{x: Number}`, `(String, Number)`, `[Date]`
|
139 | * __Fields__ = a `{`, followed one or more `Field` separated by a comma `,` (trailing comma `,` is permitted), optionally an `...` (always preceded by a comma `,`), followed by a `}` - eg. `{x: Number, y: String}`, `{k: Function, ...}`
|
140 | * __Field__ = an `Identifier`, followed by a colon `:`, followed by `Types` - eg. `x: Date | String`, `y: Boolean`
|
141 | * __Tuple__ = a `(`, followed by one or more `Types` separated by a comma `,` (trailing comma `,` is permitted), followed by a `)` - eg `(Date)`, `(Number, Date)`
|
142 | * __Array__ = a `[` followed by exactly one `Types` followed by a `]` - eg. `[Boolean]`, `[Boolean | Null]`
|
143 |
|
144 | ### Guide
|
145 |
|
146 | `type-check` uses `Object.toString` to find out the basic type of a value. Specifically,
|
147 |
|
148 | ```js
|
149 | {}.toString.call(VALUE).slice(8, -1)
|
150 | {}.toString.call(true).slice(8, -1) // 'Boolean'
|
151 | ```
|
152 | A basic type, eg. `Number`, uses this check. This is much more versatile than using `typeof` - for example, with `document`, `typeof` produces `'object'` which isn't that useful, and our technique produces `'HTMLDocument'`.
|
153 |
|
154 | You may check for multiple types by separating types with a `|`. The checker proceeds from left to right, and passes if the value is any of the types - eg. `String | Boolean` first checks if the value is a string, and then if it is a boolean. If it is none of those, then it returns false.
|
155 |
|
156 | Adding a `Maybe` in front of a list of multiple types is the same as also checking for `Null` and `Undefined` - eg. `Maybe String` is equivalent to `Undefined | Null | String`.
|
157 |
|
158 | You may add a comment to remind you of what the type is for by following an identifier with a `::` before a type (or multiple types). The comment is simply thrown out.
|
159 |
|
160 | The wildcard `*` matches all types.
|
161 |
|
162 | There are three types of structures for checking the contents of a value: 'fields', 'tuple', and 'array'.
|
163 |
|
164 | If used by itself, a 'fields' structure will pass with any type of object as long as it is an instance of `Object` and the properties pass - this allows for duck typing - eg. `{x: Boolean}`.
|
165 |
|
166 | To check if the properties pass, and the value is of a certain type, you can specify the type - eg. `Error{message: String}`.
|
167 |
|
168 | If you want to make a field optional, you can simply use `Maybe` - eg. `{x: Boolean, y: Maybe String}` will still pass if `y` is undefined (or null).
|
169 |
|
170 | If you don't care if the value has properties beyond what you have specified, you can use the 'etc' operator `...` - eg. `{x: Boolean, ...}` will match an object with an `x` property that is a boolean, and with zero or more other properties.
|
171 |
|
172 | For an array, you must specify one or more types (separated by `|`) - it will pass for something of any length as long as each element passes the types provided - eg. `[Number]`, `[Number | String]`.
|
173 |
|
174 | A tuple checks for a fixed number of elements, each of a potentially different type. Each element is separated by a comma - eg. `(String, Number)`.
|
175 |
|
176 | An array and tuple structure check that the value is of type `Array` by default, but if another type is specified, they will check for that instead - eg. `Int32Array[Number]`. You can use the wildcard `*` to search for any type at all.
|
177 |
|
178 | Check out the [type precedence](https://github.com/zaboco/type-precedence) library for type-check.
|
179 |
|
180 | ## Options
|
181 |
|
182 | Options is an object. It is an optional parameter to the `typeCheck` and `parsedTypeCheck` functions. The only current option is `customTypes`.
|
183 |
|
184 | <a name="custom-types" />
|
185 | ### Custom Types
|
186 |
|
187 | __Example:__
|
188 |
|
189 | ```js
|
190 | var options = {
|
191 | customTypes: {
|
192 | Even: {
|
193 | typeOf: 'Number',
|
194 | validate: function(x) {
|
195 | return x % 2 === 0;
|
196 | }
|
197 | }
|
198 | }
|
199 | };
|
200 | typeCheck('Even', 2, options); // true
|
201 | typeCheck('Even', 3, options); // false
|
202 | ```
|
203 |
|
204 | `customTypes` allows you to set up custom types for validation. The value of this is an object. The keys of the object are the types you will be matching. Each value of the object will be an object having a `typeOf` property - a string, and `validate` property - a function.
|
205 |
|
206 | The `typeOf` property is the type the value should be (optional - if not set only `validate` will be used), and `validate` is a function which should return true if the value is of that type. `validate` receives one parameter, which is the value that we are checking.
|
207 |
|
208 | ## Technical About
|
209 |
|
210 | `type-check` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It also uses the [prelude.ls](http://preludels.com/) library.
|