check-types-mini5.8.0

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

§ Quick Take

import { strict as assert } from "assert";
import checkTypesMini from "check-types-mini";

assert.throws(() => {
  checkTypesMini(
    checkTypesMini(
      {
        // object to check
        option1: "setting1",
        option2: "false",
        option3: false,
      },
      {
        // reference defaults object
        option1: "setting1",
        option2: false,
        option3: false,
      }
    ),
    /not boolean but string/g
  );
});

§ Purpose

Saves time in Options object validation, at expense of your program's perf:

const checkTypes = require("check-types-mini");

function yourFunction(input, originalOpts) {
// 1. declare defaults:
const defaults = { placeholderEnabled: false };
// 2. merge given opts into defaults:
const opts = Object.assign({}, defaults, originalOpts);
// 3. type check:
checkTypes(opts, defaults, {
msg: "newLibrary/yourFunction(): [THROW_ID_01]",
});

// rest of your app goes here...
}

// NOW, let's call our function with wrong opts and see what happens:
let res = yourFunction(1, { placeholderEnabled: "zzz" }); // < notice opts key was Boolean in defaults

// WE GET A TYPE ERROR THROWN:
// =>> TypeError: 'newLibrary/yourFunction(): [THROW_ID_01] opts.placeholderEnabled was customised to "zzz" which is not boolean but string'

§ 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.

Features:

  • Use a default options object to enforce types
  • Supplement or fully customise types (via a simple schema)
  • Customise error messages so that errors show source as your library, even though check-types-mini threw them

For example, here's a typical throw error generated by this library:

TypeError: yourLibrary/yourFunction(): [THROW_ID_01] opts.placeholder was customised to "false" which is not boolean but string

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.

The only drawback is, this program will affect the performance - that's why many apps don't even validate the options' values, especially boolean-ones.

§ 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 argumentTypeObligatory?Description
objPlain objectyesOptions object after user's customisation
refPlain objectno^Default options - used to compare the types
optsPlain objectnoOptional options go here.

^ref can be null or undefined if all keys are set via opts.schema (see below).

§ Options object

options object's keyTypeObligatory?DefaultDescription
ignoreKeysArray or Stringno[] (empty array)Instructs to skip all and any checks on keys, specified in this array. Put them as strings.
ignorePathsArray or Stringno[] (empty array)Instructs to skip all and any checks on keys which have given object-pathopens in a new tab notation-style path(s) within the obj. Similar thing to opts.ignoreKeys above, but unique (because simply key names can appear in multiple places whereas paths are unique).
acceptArraysBooleannofalseIf it's set to true, value can be array of elements, same type as reference.
acceptArraysIgnoreArray of strings or Stringno[] (empty array)If you want to ignore acceptArrays on certain keys, pass them in an array here.
enforceStrictKeysetBooleannotrueIf it's set to true, your object must not have any unique keys that reference object (and/or schema) does not have.
schemaPlain objectno{}You can set arrays of types for each key, overriding the reference object. This allows you more precision and enforcing multiple types.
msgStringno``A message to show. We like to include the name of the calling library, parent function and numeric throw ID.
optsVarNameStringnooptsHow is your options variable called? It does not matter much, but it's nicer to keep references consistent with your API documentation.

Here are all defaults in one place:

{
ignoreKeys: [],
ignorePaths: [],
acceptArrays: false,
acceptArraysIgnore: [],
enforceStrictKeyset: true,
schema: {},
msg: "check-types-mini",
optsVarName: "opts"
}

§ For example

The common pattern is,

  1. 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)
  2. 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.
  3. Object.assign cloned defaults onto the options object that comes from the input.
  4. call check-types-mini with the above.
  5. If input types mismatch, error will be thrown.
const checkTypes = require("check-types-mini");

function yourFunction(input, opts) {
// declare defaults, so we can enforce types later:
const defaults = {
placeholder: false,
};
// fill any settings with defaults if missing:
opts = Object.assign({}, defaults, opts);

// the check:
checkTypes(opts, defaults, {
msg: "newLibrary/yourFunction(): [THROW_ID_01]",
optsVarName: "opts",
});
// ...
}

let res = yourFunction(1, { placeholder: "zzz" });

// =>> [TypeError: 'newLibrary/yourFunction(): [THROW_ID_01] opts.placeholder was customised to "zzz" which is not boolean but string']

Sometimes you want to accept either value of certain type (like string) or array of those (like array of strings).

For example, if somebody sneaks in array with strings and one null, you want to throw.

For these cases set opts.acceptArrays to true.

This will throw an error:

const checkTypes = require("check-types-mini");
checkTypes(
{
// < input
option1: "setting1",
option2: [true, true],
option3: false,
},
{
// < reference
option1: "setting1",
option2: false,
option3: false,
}
);
// => Throws, because reference's `option2` is Boolean ("false") but input `option2` is array ("[true, true]").

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,
}
);
// => Does not throw, because we allow arrays full of a matching type

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.

§ opts.enforceStrictKeyset

When we were coding a new major version of ast-delete-object, we had to update all the unit tests too. Previously, the settings were set using only one argument, Boolean-type. We had to change it to be a plain object. We noticed that when we missed some tests, their Booleans were Object.assigned into a default settings object and no alarm was being raised! That's not good.

Then we 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 we 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.

§ 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", // << notice, it's given as string in defaults object
},
{
schema: {
option2: ["stRing", null],
},
}
);
// => does not throw

The types are case-insensitive and come from type-detectopens in a new tab, a Chai library:

  • 'object' (meaning a plain object literal, nothing else)
  • 'array'
  • 'string'
  • 'null'
  • and other usual types

Also, you can use more specific subtypes:

  • 'true'
  • 'false'

The 'true' and 'false' are handy in cases when API's accept only one of them, for example, 'false' and 'string', but doesn't accept 'true'.

For example,

const res = checkTypes(
{
// <--- this is object we're checking
option1: "setting1",
option2: true, // <--- bad
},
{
// <--- this is default reference object
option1: "zz",
option2: null,
},
{
// <--- opts
schema: {
option2: ["null", "false", "string"],
},
}
);
// => throws an error because `option2` should be either false or string, not true

All the type values you put into opts.schema are not validated, on purpose, so please don't make typos.

§ 2020 update

At first, we aimed to put check-types-mini on every npm package that uses options. Then, we became aware of JS performance and started to remove strict input validation, especially in case of booleans and one-level plain objects.

When the program has complex input object and you want to validate it, check-types-mini is your best friend.

For example, ast-monkey has complex options and needs validation help.

But for one-level-deep options objects, check-types-mini is an overkill (unless you don't care about perf).

§ Licence

MITopens in a new tab

Copyright © 2010–2020 Roy Revelt and other contributors

Related packages:

📦 all-named-html-entities 1.3.7
List of all named HTML entities
📦 array-includes-with-glob 2.12.42
like _.includes but with wildcards
📦 array-of-arrays-sort-by-col 2.12.13
sort array of arrays by column, rippling the sorting outwards from that column
📦 array-group-str-omit-num-char 2.1.48
Groups array of strings by omitting number characters
📦 array-of-arrays-into-ast 1.9.50
turns an array of arrays of data into a nested tree of plain objects
📦 array-pull-all-with-glob 4.12.72
pullAllWithGlob - like _.pullAll but pulling stronger, with globs
📦 arrayiffy-if-string 3.11.38
Put non-empty strings into arrays, turn empty-ones into empty arrays. Bypass everything else.