check-types-mini

Check the types of your options object's values after user has customised them

Table of Contents
Install
npm i check-types-mini
Consume:
const checkTypes = require('check-types-mini')
import checkTypes from 'check-types-mini'
Here's what you'll get:
Type | Key in package.json | Path | Size |
---|
Main export - CommonJS version, transpiled to ES5, contains require and module.exports | main | dist/check-types-mini.cjs.js | 7 KB |
ES module build that Webpack/Rollup understands. Untranspiled ES6 code with import /export . | module | dist/check-types-mini.esm.js | 7 KB |
UMD build for browsers, transpiled, minified, containing iife 's and has all dependencies baked-in | browser | dist/check-types-mini.umd.js | 15 KB |
⬆ back to top
Idea
Imagine you have a library where you let users set the options object which comes as one of the input arguments.
Here's a challenge: how do you check (and throw) errors, easily, when users set your options to wrong things?
Answer: this library. It does all the work validating the inputs, lets you customise the throw
error messages (like below) and even lets you provide the schema, that is, array of allowed types that each options key's value should be in.
For example, here's a typical throw error generated by this library:
TypeError: fancyLibrary/fancyFunction(): [THROW_ID_01] opts.placeholder was customised to "false" which is not boolean but string
Originally this library started as a function within one of my libraries. When I was about to copy-paste the thing into another library, I stopped and put that into a separate library, this library. I'm glad I did it, because already 7 22 26 of my libraries depend on it, and improving check-types
I improve my other libraries. DRY at its best. Feel free to tap check-types-mini
in your libraries!
The point of check-types-mini
is to save your time: time spent coding up all these checks, time spent debugging, and even consumers' time spent debugging your API when they try to use it wrongly. Every library that has options object will need some type checks if you let user tinker with it.
⬆ back to top
API
checkTypes(obj[, ref^, opts])
Use it by calling its function. You don't need to assign it to anything - good outcome is nothing happens, bad outcode is error thrown.
Technically speaking, the main and only job of check-types-mini
is to throw errors when your library's consumers are using it wrongly. Error messages can be customised:
Input argument | Type | Obligatory? | Description |
---|
obj | Plain object | yes | Options object after user's customisation |
ref | Plain object | no^ | Default options - used to compare the types |
opts | Plain object | no | Optional options go here. |
^ref
can be null
or undefined
if all keys are set via opts.schema
(see below).
⬆ back to top
Options object
options object's key | Type | Obligatory? | Default | Description |
---|
{ | | | | |
ignoreKeys | Array or String | no | [] (empty array) | Instructs to skip all and any checks on keys, specified in this array. Put them as strings. |
acceptArrays | Boolean | no | false | If it's set to true , value can be array of elements, same type as reference. |
acceptArraysIgnore | Array of strings or String | no | [] (empty array) | If you want to ignore acceptArrays on certain keys, pass them in an array here. |
enforceStrictKeyset | Boolean | no | true | If it's set to true , your object must not have any unique keys that reference object (and/or schema ) does not have. |
schema | Plain object | no | {} | You can set arrays of types for each key, overriding the reference object. This allows you more precision and enforcing multiple types. |
msg | String | no | | A message to show. I like to include the name of the calling library, parent function and numeric throw ID. |
optsVarName | String | no | opts | How is your options variable called? It does not matter much, but it's nicer to keep references consistent with your API documentation. |
} | | | | |
⬆ back to top
For example
The common pattern is,
- a) Define defaults object. Later it will be used to validate user's options, PLUS, if that's not enough, you can allow users to provide arrays of the matching type (set
opts.acceptArrays
to true
) - b) Alternatively, you can skip defaults object and provide schema for each key via
opts.schema
. Just stick an object there, as a value, with all keys. Put allowed types in an array. Object.assign
cloned defaults onto the options object that comes from the input.- call
check-types-mini
with the above. - If input types mismatch, error will be
throw
n.
const checkTypes = require('check-types-mini')
function yourFunction (input, opts) {
const defaults = {
placeholder: false
}
opts = Object.assign({}, defaults, opts)
checkTypes(opts, defaults, {msg: 'newLibrary/yourFunction(): [THROW_ID_01]', optsVarName: 'opts'})
}
let res = yourFunction(1, {placeholder: 'zzz'})
Sometimes you want to accept either a string (or type "X") or an arrays of strings (elements of type "X"). As long as ALL the elements within the array match the reference type, it's OK. For these cases set opts.acceptArrays
to true
.
This will throw:
const checkTypes = require('check-types-mini')
checkTypes(
{
option1: 'setting1',
option2: [true, true],
option3: false
},
{
option1: 'setting1',
option2: false,
option3: false
}
)
But when we allow arrays of the matching type, it won't throw anymore:
const checkTypes = require('check-types-mini')
checkTypes(
{
option1: 'setting1',
option2: ['setting3', 'setting4'],
option3: false
},
{
option1: 'setting1',
option2: 'setting2',
option3: false
},
{
acceptArrays: true
}
)
If you want, you can blacklist certain keys of your objects so that opts.acceptArrays
will not apply to them. Just add keys into opts.acceptArraysIgnore
array.
⬆ back to top
opts.enforceStrictKeyset
When I was coding a new major version of posthtml-ast-delete-object I had to update all the unit tests too. Previously, the settings were set using only one argument, Boolean-type. I had to change it to be a plain object. I noticed that when I missed updating some tests, their Booleans were Object.assign
ed into a default settings object and no alarm was being raised! That's not good.
Then I came up with the idea to enforce the keys of the object to match the reference and/or schema keys in options
. It's on by default because I can't imagine how you would end up with settings object that does not match your default settings object, key-wise, but if you don't like that, feel free to turn it off. It's opts.enforceStrictKeyset
Boolean flag.
⬆ back to top
opts.schema
Sometimes your API is more complex than a single type or array of them. Sometimes you want to allow, let's say, string
or array
of strings or null
. What do you do?
Enter opts.schema
. You can define all the types for particular key, as an array:
const checkTypes = require('check-types-mini')
checkTypes(
{
option1: 'setting1',
option2: null
},
{
option1: 'zz',
option2: 'yy'
},
{
schema: {
option2: ['stRing', null]
}
}
)
The types are case-insensitive and come from type-detect, a Chai library:
object
(meaning a plain object literal, nothing else)array
string
null
- and other usual types
The type values you put into opts.schema
are not validated, on purpose, so please don't make typos.
⬆ back to top
Contributing
Hi! 99% of people in the society are passive - consumers. They wait for others to take action, they prefer to blend in. The remaining 1% are proactive citizens who will do something rather than wait. If you are one of that 1%, you're in luck because I am the same and together we can make something happen.
-
If you want a new feature in this package or you would like to change some of its functionality, raise an issue on this repo. Also, you can email me. Just let it out.
-
If you tried to use this library but it misbehaves, or you need an advice setting it up, and its readme doesn't make sense, just document it and raise an issue on this repo. Alternatively, you can email me.
-
If you don't like the code in here and would like to give advice about how something could be done better, please do. Same drill - GitHub issues or email, your choice.
-
If you would like to add or change some features, just fork it, hack away, and file a pull request. I'll do my best to merge it quickly. Code style is airbnb-base
, only without semicolons. If you use a good code editor, it will pick up the established ESLint setup.
⬆ back to top
Licence
MIT License (MIT)
Copyright © 2018 Codsen Ltd, Roy Revelt