mini-type-assert
Concise type assertions like a<map<fn:s>>
. Expressions are parsed just once: it generates functions and caches them. Supports the types of kind-of and has short aliases for most.
example
const t = { thisage = thismixed = thisstore = // Spaces are allowed thiswords = // Or use placeholders thiswords = // Throw if a is defined and not a boolean const a = false } = } // Instantiate maps with key-value pairsconst goodboy = {} /a/ const badboy = 'not a function' /a/ // Okay27 1 'a' 'beep' goodboy a: true // Throws'bad' null 'BEEP' badboy a: 0
decorator
If you like ES7 decorators, check out mini-type-decorator.
const t = @ { thistags = tags } @ { console }
t(value, assertion, name, ...placeholders)
The first three arguments are required. Throws if value
does not pass assertion
. Otherwise, returns value
. The name
will be used in the error message.
assertions
If assertion
is a string or regular expression, it will be treated as a type expression (see below). If it's a function, it will receive the value and should return false
if the value is invalid. A boolean assertion
works like assert(assertion === true)
. If assertion
is an array, each element must pass assertion. For example, to assert that an argument is a number and greater than two: t(arg, ['n', (v) => v > 2 ], 'arg')
.
type expressions
- Aliases:
a<s|f>
isarr<str|fn>
isarray<string|function>
. See the full list. - Member types:
a<n>
(an array of numbers). Note that the entire iterable (array, object, map, ..) will be traversed, so use it wisely. - Member key types:
map<r:n>
(a Map with regular expressions for keys and numbers for values). Again, traversed entirely. Key types are ignored for arrays (can only be numbers) and objects (can only be strings). - OR:
n|s
(a number or string) - Regular expressions:
/\d/
(a string containing at least one number)a < /^x$/i >
(an array containing "x" or "X" strings)map < /^[a-z]+$/ : /^[a-z]+$/ >
(a Map with lowercase strings for both keys and values)
- Negation:
!fn
(anything but a function) - Whitespace:
s | a
iss|a
. Except within regular expressions, spaces are ignored. - Operator precedence:
s|a<n|b>
(a string, or an array containing numbers or booleans) - Placeholders:
t(1, '$|$', 'arg', 's', 'n')
is the same ast(1, 's|n', 'arg')
install
With npm do:
npm install mini-type-assert --save
license
MIT © Vincent Weevers