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 argument | Type | Required | Description |
|---|---|---|---|
objType: Plain object | |||
obj | Plain object | yes | The resolved or user-supplied options to validate. Root arrays and class instances are rejected. |
refType: Plain object or null | |||
ref | Plain object or null | yes | A reference object used to infer types. Pass null explicitly for schema-only validation. |
optsType: Plain object or null | |||
opts | Plain object or null | no | Validator controls. null and undefined both select the defaults. |
The optional options object has the following shape:
| Key | Type | Default | Description |
|---|---|---|---|
acceptArraysType: Boolean Default: false | |||
acceptArrays | Boolean | false | Let an option contain an array whose present elements each satisfy the scalar reference or schema predicate. |
acceptArraysIgnoreType: String or read-only string array Default: [] | |||
acceptArraysIgnore | String or read-only string array | [] | Disable acceptArrays for matching key names. |
enforceStrictKeysetType: Boolean Default: true | |||
enforceStrictKeyset | Boolean | true | Reject uncovered object-property keys and missing root keys required by the reference object. |
ignoreKeysType: String or read-only string array Default: [] | |||
ignoreKeys | String or read-only string array | [] | Skip a matching object-property key at every object level. |
ignorePathsType: String or read-only string array Default: [] | |||
ignorePaths | String or read-only string array | [] | Skip a matching complete path written in dot notation. |
msgType: String Default: check-types-mini | |||
msg | String | check-types-mini | Context included in validator errors, such as buildConfig. This does not replace the validator’s own package/function prefix. |
optsVarNameType: String Default: opts | |||
optsVarName | String | opts | Variable name used when formatting paths in error messages. |
reportCompletionFuncType: Function or nullDefault: null | |||
reportCompletionFunc | Function or null | null | Receive frozen completion statistics after successful validation. |
reportProgressFuncType: Function or nullDefault: null | |||
reportProgressFunc | Function or null | null | Receive finite, monotonic progress values. |
reportProgressFuncFromType: Number Default: 0 | |||
reportProgressFuncFrom | Number | 0 | Finite start of the reported progress range. |
reportProgressFuncToType: Number Default: 100 | |||
reportProgressFuncTo | Number | 100 | Finite end of the reported progress range. Must not be lower than the start. |
schemaType: Plain object Default: {} | |||
schema | Plain 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:
| Type | Description |
|---|---|
ObjType: Obj | |
Obj | The object-shaped public root type. Runtime validation narrows it to a plain object. |
Schema, SchemaDescriptor, SchemaTypeNameType: Schema, SchemaDescriptor, SchemaTypeName | |
Schema, SchemaDescriptor, SchemaTypeName | Recursive schema shapes and their allowed descriptor values. |
OptsType: Opts | |
Opts | The validator options documented above. |
CompletionStatsType: CompletionStats | |
CompletionStats | Counters supplied to reportCompletionFunc. |
CheckTypesMiniThrowIdType: CheckTypesMiniThrowId | |
CheckTypesMiniThrowId | Stable validator error-code union. |
CheckTypesMiniErrorDetails, CheckTypesMiniErrorJsonType: CheckTypesMiniErrorDetails, CheckTypesMiniErrorJson | |
CheckTypesMiniErrorDetails, CheckTypesMiniErrorJson | Structured 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-detect, 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:
| Field | Description |
|---|---|
validatorCode | |
validatorCode | Stable THROW_ID_XX identifying the validator branch. |
path | |
path | Read-only property-path segments related to the failure. |
expectedTypes | |
expectedTypes | Read-only expected type names, or null when not applicable. |
actualType | |
actualType | Detected type name, or null when not applicable. |
context | |
context | The normalized msg option. |
reason | |
reason | Error 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 field | Description |
|---|---|
arrayElementsVisited | |
arrayElementsVisited | Present array elements inspected. Sparse holes are not visited. |
maxDepth | |
maxDepth | Deepest input or schema path reached, with root properties at depth 1. |
objectPropertiesVisited | |
objectPropertiesVisited | Input object properties inspected. |
schemaEntries | |
schemaEntries | Normalized schema entries. |
timeTakenInMilliseconds | |
timeTakenInMilliseconds | Best-effort elapsed time measured only when completion reporting is enabled. |
valuesIgnored | |
valuesIgnored | Values pruned by an ignore rule or blanket schema. |
valuesValidated | |
valuesValidated | Schema 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.