tcomb-validation
tcomb-validation is a general-purpose JavaScript validation library built upon the tcomb type combinator library. It provides a concise yet expressive syntax for validating various data structures, including native types, refinements, objects, lists, tuples, enums, unions, dicts, and intersections, with arbitrary nesting levels. The library offers detailed information on failed validations, making it a lightweight alternative to JSON Schema for validating domain models. The current stable version is 3.4.1, with releases typically addressing bug fixes and minor features, often in conjunction with its `tcomb` dependency. A key differentiator is its direct reuse of `tcomb` type definitions for validation, streamlining development when `tcomb` is already used for runtime type checking or domain modeling. It ships with TypeScript definitions, ensuring good type safety for modern JavaScript and TypeScript projects.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'String')
cause The `tcomb` library, which defines types like `t.String`, was not imported or was imported incorrectly (e.g., trying to use `t` from `tcomb-validation`).fixEnsure `tcomb` is installed (`npm install tcomb`) and correctly imported, typically as `t`: `import * as t from 'tcomb';` or `const t = require('tcomb');`. -
TypeError: validate is not a function
cause The `validate` function was not imported correctly from `tcomb-validation`, or `tcomb-validation` itself wasn't properly installed.fixUse a named import for `validate`: `import { validate } from 'tcomb-validation';` or for CommonJS: `const { validate } = require('tcomb-validation');`. -
TS2345: Argument of type 'string' is not assignable to parameter of type 'Number'.
cause A value of an incorrect type was provided to `validate` against a `tcomb` type, and TypeScript's static analysis caught a potential runtime validation failure.fixAdjust the data being validated to match the expected `tcomb` type, or refine the `tcomb` type definition to correctly represent the allowable data shapes.
Warnings
- breaking The behavior of `maybe(MyType)(undefined)` changed in v3.0.0. Previously it returned `null`, but after the upgrade to `tcomb` v3.0.0, it no longer implicitly converts `undefined` to `null`.
- breaking The `path` argument to the `validate` function was replaced by a more flexible `options` object in v2.2.0. Passing a plain array as the `path` is now deprecated.
- gotcha To define types for validation (e.g., `t.String`, `t.struct`, `t.refinement`), you *must* explicitly import and use the `tcomb` library alongside `tcomb-validation`. `tcomb-validation` does not re-export `tcomb`'s type combinators.
- gotcha Users of TypeScript with complex or recursive type definitions might encounter type definition errors with versions prior to v3.4.1.
Install
-
npm install tcomb-validation -
yarn add tcomb-validation -
pnpm add tcomb-validation
Imports
- validate
const validate = require('tcomb-validation');import { validate } from 'tcomb-validation'; - ValidationResult
import ValidationResult from 'tcomb-validation/ValidationResult';
import { ValidationResult } from 'tcomb-validation'; - tcomb types
const t = require('tcomb-validation');import * as t from 'tcomb';
Quickstart
import * as t from 'tcomb';
import { validate } from 'tcomb-validation';
// Define a type using tcomb
const UserName = t.refinement(t.String, (s) => s.length > 3 && s.length < 20, 'UserName');
// Define a struct (object type)
const User = t.struct({
id: t.Number,
name: UserName,
email: t.maybe(t.String) // optional email
}, 'User');
// Validate a valid object
const validUser = { id: 1, name: 'JohnDoe', email: 'john.doe@example.com' };
let result = validate(validUser, User);
console.log('Valid user result:', result.isValid()); // true
// Validate an invalid object
const invalidUser = { id: 'a', name: 'Jo', age: 30 }; // id wrong type, name too short, extra prop
result = validate(invalidUser, User, { strict: true }); // strict mode to disallow extra props
console.log('Invalid user result:', result.isValid()); // false
console.log('First error:', result.firstError()?.message);
// Inspect all errors
result.errors.forEach(error => {
console.log(`Path: ${error.path.join('.')}, Value: ${error.value}, Message: ${error.message}`);
});
/* Expected output for invalidUser (may vary slightly based on tcomb-validation version):
Path: id, Value: a, Message: Invalid value "a" supplied to Number
Path: name, Value: Jo, Message: Invalid value "Jo" supplied to UserName
Path: age, Value: 30, Message: Invalid key "age" supplied to User
*/