What is tcomb?
The tcomb npm package is a library for Node.js and the browser which allows you to check the types of JavaScript values at runtime with a simple and concise syntax. It is useful for enforcing type safety, defining domain models, and creating composable and reusable type checkers.
What are tcomb's main functionalities?
Type Checking
This feature allows you to define a structure with specific types and create instances that adhere to those types.
const t = require('tcomb');
const Person = t.struct({ name: t.String, age: t.Number });
const person = Person({ name: 'Giulio', age: 43 });
Function Argument Validation
This feature enables you to validate function arguments to ensure they are of the expected type.
const t = require('tcomb');
function sum(a, b) {
t.Number(a);
t.Number(b);
return a + b;
}
sum(1, 2);
Subtyping
This feature allows you to create subtypes based on existing types with additional constraints.
const t = require('tcomb');
const Positive = t.subtype(t.Number, n => n >= 0);
const positiveNumber = Positive(10);
Refinement
This feature is similar to subtyping but is specifically for refining types to a more specific subset.
const t = require('tcomb');
const Integer = t.refinement(t.Number, n => n % 1 === 0);
const integerNumber = Integer(42);
Enums
This feature allows you to define a set of constants and ensure values match one of those constants.
const t = require('tcomb');
const Role = t.enums({ Admin: 'Admin', User: 'User' });
const userRole = Role('User');
Other packages similar to tcomb
prop-types
Prop-types is a library for React that is used to document the intended types of properties passed to components. It is similar to tcomb in that it provides runtime type checking, but it is specifically tailored for React's component props.
io-ts
io-ts is a TypeScript runtime type system for IO decoding/encoding. It is similar to tcomb in providing runtime type checking and validation, but it leverages TypeScript's type system for added compile-time safety.
joi
Joi is an object schema description language and validator for JavaScript objects. It provides a powerful and expressive way to define and validate data structures. It is similar to tcomb in terms of validation capabilities but has a different API and is often used for validating API input.
ajv
Ajv is a JSON schema validator. It validates data against JSON Schema standards and is similar to tcomb in terms of validation. However, it uses a JSON-based schema definition rather than a programmatic API.
"Si vis pacem, para bellum" - (Vegetius 5th century)
tcomb is a library for Node.js and the browser which allows you to check the types of JavaScript values at runtime with a simple and concise syntax. It's great for Domain Driven Design and for adding safety to your internal code.
Setup
npm install tcomb --save
Code example
A type-checked function:
import t from 'tcomb';
function sum(a, b) {
t.Number(a);
t.Number(b);
return a + b;
}
sum(1, 's');
function sum(a: number, b: number) {
return a + b;
}
A user defined type:
const Integer = t.refinement(t.Number, (n) => n % 1 === 0, 'Integer');
A type-checked class:
const Person = t.struct({
name: t.String,
surname: t.maybe(t.String),
age: Integer,
tags: t.list(t.String)
}, 'Person');
Person.prototype.getFullName = function () {
return `${this.name} ${this.surname}`;
};
const person = Person({
surname: 'Canti'
});
Chrome DevTools:
Docs
Features
Lightweight
3KB gzipped, no dependencies.
Type safety
All models defined with tcomb
are type-checked.
Note. Instances are not boxed, this means that tcomb
works great with lodash, Ramda, etc. And you can of course use them as props to React components.
Based on set theory
Domain Driven Design
Write complex domain models in a breeze and with a small code footprint. Supported types / combinators:
- user defined types
- structs
- lists
- enums
- refinements
- unions
- intersections
- the option type
- tuples
- dictionaries
- functions
- recursive and mutually recursive types
- interfaces
Immutability and immutability helpers
Instances are immutable using Object.freeze
. This means you can use standard JavaScript objects and arrays. You don't have to change how you normally code. You can update an immutable instance with the provided update(instance, spec)
function:
const person2 = Person.update(person, {
name: { $set: 'Guido' }
});
where spec
is an object containing commands. The following commands are compatible with the Facebook Immutability Helpers:
$push
$unshift
$splice
$set
$apply
$merge
See Updating immutable instances for details.
Speed
Object.freeze
calls and asserts are executed only in development and stripped out in production (using process.env.NODE_ENV !== 'production'
tests).
Runtime type introspection
All models are inspectable at runtime. You can read and reuse the informations stored in your types (in the meta
static member). See The meta object in the docs for details.
Libraries exploiting tcomb's RTI:
Easy JSON serialization / deseralization
Encodes / decodes your domain models to / from JSON for free.
Debugging with Chrome DevTools
You can customize the behavior when an assert fails leveraging the power of Chrome DevTools.
t.fail = function fail(message) {
throw new TypeError('[tcomb] ' + message);
};
t.fail = function fail(message) {
console.error(message);
};
Pattern matching
const result = t.match(1,
t.String, () => 'a string',
t.Number, () => 'a number'
);
console.log(result);
Babel plugin
Using babel-plugin-tcomb you can also write (Flow compatible) type annotations:
function sum(a: number, b: number): number {
return a + b;
}
TypeScript definition file
index.d.ts
Contributors
How to Build a standalone bundle
git clone git@github.com:gcanti/tcomb.git
cd tcomb
npm install
npm run dist
Will output 2 files:
dist/tcomb.js
(development)dist/tcomb.min.js
(production) Object.freeze
calls and asserts stripped out
Related libraries
Similar projects
License
The MIT License (MIT)