Skip to Content
  • Website
Codsen
  • Home
  • Open Source
  • Articles
  • About

prevOpen Source→check-types-mininext

check-types-mini8.2.4

Validate options object

Downloads per monthChangelogMIT Licenselibera manifesto
  • the top
  • Installation
  • Quick Take
  • Examples
  • IDEA
  • API — CHECKTYPESMI…
  • API — DEFAULTS
  • API — VERSION
  • API — TYPES
  • FOR EXAMPLE
  • OPTS — ACCEPTARRAYS
  • OPTS — ENFORCESTRIC…
  • OPTS — SCHEMA
  • IGNORE RULES
  • ERRORS
  • PROGRESS AND…
  • TRAVERSAL AND…
  • REGARDING TYP…
  • Changelog

No 3rd party dependencies. All dependencies and devDependencies, checked recursively, are Codsen packages.

Permalink to InstallationInstallation

Permalink to Quick TakeQuick Take

Permalink to ExamplesExamples

  • Exclude selected paths from array acceptance
  • Accept arrays of the reference value's type
  • Allow any shape below a schema path
  • Customise validation error context
  • Ignore a key wherever it occurs
  • Ignore only selected nested paths
  • Validate a property whose key contains a literal dot
  • Use a nested schema object
  • Compose progress and inspect completion statistics
  • Allow missing and additional keys
  • Allow multiple types through a schema
  • Validate an options object against defaults

Idea

Many packages accept an options object. TypeScript can check typed callers, but JavaScript, JSON, and other runtime inputs can still contain unknown keys or values of the wrong type.

check-types-mini validates a plain options object against a reference object, a schema, or both. It walks nested objects iteratively, so deeply nested input does not depend on the JavaScript call stack.

Features:

  • Infer expected types from a reference object.
  • Supplement or replace the reference with flat or nested schema entries.
  • Reject unknown keys when strict keyset enforcement is enabled.
  • Apply case-sensitive wildcard ignore rules to keys or complete paths.
  • Report structured errors, progress, and completion statistics.

For example, a failed reference comparison throws a structured CheckTypesMiniError:

CheckTypesMiniError: check-types-mini/checkTypesMini(): [THROW_ID_21] buildConfig: opts.placeholder was customised to "false" which is not boolean but string

Validation has a runtime cost, so use it where a public or otherwise untrusted configuration boundary benefits from clear failures.

API - checkTypesMini()

The main function checkTypesMini() is imported like this:

It’s a function which takes three input arguments:

The function returns undefined after successful validation and throws when the contract is not met.

Input argumentTypeRequiredDescription
obj
Type: Plain object
objPlain objectyesThe resolved or user-supplied options to validate. Root arrays and class instances are rejected.
ref
Type: Plain object or null
refPlain object or nullyesA reference object used to infer types. Pass null explicitly for schema-only validation.
opts
Type: Plain object or null
optsPlain object or nullnoValidator controls. null and undefined both select the defaults.

The optional options object has the following shape:

KeyTypeDefaultDescription
acceptArrays
Type: Boolean
Default: false
acceptArraysBooleanfalseLet an option contain an array whose present elements each satisfy the scalar reference or schema predicate.
acceptArraysIgnore
Type: String or read-only string array
Default: []
acceptArraysIgnoreString or read-only string array[]Disable acceptArrays for matching key names.
enforceStrictKeyset
Type: Boolean
Default: true
enforceStrictKeysetBooleantrueReject uncovered object-property keys and missing root keys required by the reference object.
ignoreKeys
Type: String or read-only string array
Default: []
ignoreKeysString or read-only string array[]Skip a matching object-property key at every object level.
ignorePaths
Type: String or read-only string array
Default: []
ignorePathsString or read-only string array[]Skip a matching complete path written in dot notation.
msg
Type: String
Default: check-types-mini
msgStringcheck-types-miniContext included in validator errors, such as buildConfig. This does not replace the validator’s own package/function prefix.
optsVarName
Type: String
Default: opts
optsVarNameStringoptsVariable name used when formatting paths in error messages.
reportCompletionFunc
Type: Function or null
Default: null
reportCompletionFuncFunction or nullnullReceive frozen completion statistics after successful validation.
reportProgressFunc
Type: Function or null
Default: null
reportProgressFuncFunction or nullnullReceive finite, monotonic progress values.
reportProgressFuncFrom
Type: Number
Default: 0
reportProgressFuncFromNumber0Finite start of the reported progress range.
reportProgressFuncTo
Type: Number
Default: 100
reportProgressFuncToNumber100Finite end of the reported progress range. Must not be lower than the start.
schema
Type: Plain object
Default: {}
schemaPlain object{}Flat or nested type constraints. A schema entry overrides the reference value at the same path.

Every supplied option is validated. Except for the two callback fields, an explicit null is invalid; omit the field or pass undefined to use its default.

Here are all defaults in one place for copying:

API — defaults

You can import defaults:

It's a plain object:

The main function calculates the options to be used by merging the options you passed with these defaults.

API — version

You can import version:

API — types

This package is written in TypeScript and exports the following public types:

TypeDescription
Obj
Type: Obj
ObjThe object-shaped public root type. Runtime validation narrows it to a plain object.
Schema, SchemaDescriptor, SchemaTypeName
Type: Schema, SchemaDescriptor, SchemaTypeName
Schema, SchemaDescriptor, SchemaTypeNameRecursive schema shapes and their allowed descriptor values.
Opts
Type: Opts
OptsThe validator options documented above.
CompletionStats
Type: CompletionStats
CompletionStatsCounters supplied to reportCompletionFunc.
CheckTypesMiniThrowId
Type: CheckTypesMiniThrowId
CheckTypesMiniThrowIdStable validator error-code union.
CheckTypesMiniErrorDetails, CheckTypesMiniErrorJson
Type: CheckTypesMiniErrorDetails, CheckTypesMiniErrorJson
CheckTypesMiniErrorDetails, CheckTypesMiniErrorJsonStructured error construction and serialization shapes.
import type {
  CompletionStats,
  Obj,
  Opts,
  Schema,
} from "check-types-mini";

For example

A common pattern is to resolve your defaults, then validate the result against the same default object:

import { checkTypesMini } from "check-types-mini";

const reference = {
  placeholder: false,
  output: "dist",
};

function build(userOptions = {}) {
  const options = { ...reference, ...userOptions };
  checkTypesMini(options, reference, {
    msg: "buildConfig",
    optsVarName: "options",
  });
  return options;
}

build({ placeholder: "yes" });
// Throws CheckTypesMiniError with validatorCode "THROW_ID_21".

Use null as the reference when the schema is the complete contract:

import { checkTypesMini } from "check-types-mini";

checkTypesMini(
  {
    config: {
      enabled: true,
      output: "dist",
    },
  },
  null,
  {
    schema: {
      config: {
        enabled: "boolean",
        output: "string",
      },
    },
  },
);

opts.acceptArrays

Set acceptArrays to true when an option may contain either one value or an array of values of the same type:

import { checkTypesMini } from "check-types-mini";

checkTypesMini(
  {
    formats: ["esm", "iife"],
  },
  {
    formats: "esm",
  },
  {
    acceptArrays: true,
  },
);

When acceptArrays admits an array for a scalar reference or schema predicate, every present element is checked, including an explicit undefined. Sparse holes are skipped. Object-valued elements use top-level type validation; their nested fields are not compared with the scalar reference. A schema that directly accepts array, or a blanket schema, accepts the array itself and stops there. acceptArraysIgnore disables scalar-to-array acceptance for selected key names.

opts.enforceStrictKeyset

Strict keyset enforcement is enabled by default. It rejects object-property keys that are absent from both the reference and schema. When a reference object is supplied, all of its non-ignored root keys remain required even if the schema covers only some keys. Schema-only keys are allowed but optional. Nested reference keys are also optional, preserving the package’s historical behavior.

Set enforceStrictKeyset to false only when uncovered object-property keys are intentionally allowed.

opts.schema

Use a schema when a reference value is not precise enough or when you do not have a reference object. A descriptor can be one type name or a non-empty array of allowed type names:

import { checkTypesMini } from "check-types-mini";

checkTypesMini(
  {
    output: null,
  },
  {
    output: "dist",
  },
  {
    schema: {
      output: ["string", null],
    },
  },
);

Type names are case-insensitive and follow type-detectopens in a new tab, including array, string, number, null, undefined, and function. The object descriptor accepts only a plain object, not a class instance, Date, Map, or other built-in object. The string descriptors "true" and "false" distinguish Boolean values; "boolean" accepts either.

The descriptor container is validated: it must be a string, null, undefined, or a dense, non-empty array of those values. Non-empty string names are normalized but not checked against a fixed registry. Schema normalization therefore does not reject misspelled or custom type names; validation fails only when the descriptor does not match the runtime label.

Flat and nested schema spellings are equivalent:

checkTypesMini({ config: { enabled: true } }, null, {
  schema: {
    "config.enabled": "boolean",
  },
});

checkTypesMini({ config: { enabled: true } }, null, {
  schema: {
    config: {
      enabled: "boolean",
    },
  },
});

An unescaped dot separates path segments. Escape a literal dot in a property name with \.; in a JavaScript string literal, write the backslash itself as \\:

checkTypesMini({ "file.name": "index.js" }, null, {
  schema: { "file\\.name": "string" },
});

The blanket names all, any, anything, every, everything, whatever, and whatevs accept the value and stop traversal below that path. A leaf object descriptor also checks only that value’s top-level type. Add nested schema entries when child fields need validation.

Ignore rules

ignoreKeys, ignorePaths, and acceptArraysIgnore use case-sensitive whole-string wildcard matching. * matches zero or more characters. JavaScript property names are case-sensitive, so Config does not match config.

ignoreKeys applies a key pattern to object properties at every object level; it does not match array indexes. Use ignorePaths when an index must be addressed. ignorePaths applies a pattern to the complete dot-separated path; escape a dot that belongs to a literal key as \.. Pattern arrays form one allow/deny list; a leading ! excludes a match from the positive patterns:

checkTypesMini(input, reference, {
  ignorePaths: ["config.*", "!config.required"],
});

Escape a literal leading exclamation mark or asterisk as \\! or \\* in a JavaScript string.

Errors

Failures produced by the validator are CheckTypesMiniError instances and begin with a stable validator prefix:

check-types-mini/checkTypesMini(): [THROW_ID_XX]

The exported error class extends TypeError and exposes fields that do not require parsing prose:

FieldDescription
validatorCode
validatorCodeStable THROW_ID_XX identifying the validator branch.
path
pathRead-only property-path segments related to the failure.
expectedTypes
expectedTypesRead-only expected type names, or null when not applicable.
actualType
actualTypeDetected type name, or null when not applicable.
context
contextThe normalized msg option.
reason
reasonError detail without the validator prefix or context.
toJSON()
toJSON()A plain, JSON-representable projection of all structured fields plus the message and name.

If another package catches and rethrows the error, give the caller its own package/function prefix and throw ID while retaining the original error as the cause. The msg option supplies context; it does not overwrite validator provenance.

Progress and completion

Progress callbacks receive finite, monotonic values within reportProgressFuncFrom and reportProgressFuncTo. Successful validation reports both range endpoints; large traversals can also report sampled intermediate values. Completion is called only after successful validation and receives a frozen object:

Completion fieldDescription
arrayElementsVisited
arrayElementsVisitedPresent array elements inspected. Sparse holes are not visited.
maxDepth
maxDepthDeepest input or schema path reached, with root properties at depth 1.
objectPropertiesVisited
objectPropertiesVisitedInput object properties inspected.
schemaEntries
schemaEntriesNormalized schema entries.
timeTakenInMilliseconds
timeTakenInMillisecondsBest-effort elapsed time measured only when completion reporting is enabled.
valuesIgnored
valuesIgnoredValues pruned by an ignore rule or blanket schema.
valuesValidated
valuesValidatedSchema or reference predicates evaluated.

Reporting is observational. Errors thrown by either callback are ignored and cannot alter the validation result.

Traversal and data model

The validator traverses own enumerable string keys. It ignores inherited, symbol, and non-enumerable properties. For arrays it visits own, present indexes and ignores sparse holes and extra properties. It does not mutate the input, reference, schema, pattern arrays, or defaults. Each visited property is read once per traversal occurrence.

Shared acyclic object references are supported. Cyclic input paths reached during traversal and cyclic schemas throw branded validator errors instead of overflowing the call stack. A cycle below an ignored or terminal schema path is not visited.

Regarding TypeScript

TypeScript checks typed source during development; it does not add runtime validation to emitted JavaScript. Values arriving from JavaScript callers, configuration files, network responses, or unsafe casts can still violate their declared types.

Use check-types-mini at boundaries where those runtime diagnostics justify the additional work. For small internal option objects whose values are already trusted, normal TypeScript types and default merging are usually sufficient.

For example, ast-monkey uses this package to validate its public method options while still shipping TypeScript declarations.

Permalink to changelogChangelog

Open Changelog
↑ back to top
prev next

Copyright

All rights reserved © Roy Revelt 2026
All our open source packages are under MIT licenceopens in a new tab

Activities

🐛 See a bug? Raise an issueopens in a new tab
💘 Check out the Indiewebopens in a new tab and Libera manifestoopens in a new tab