"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.
import t from 'tcomb';function sum(a, b) { t.Number(a); t.Number(b); return a + b;}sum(1, 's'); // throws '[tcomb] Invalid value "s" supplied to Number'// using babel-plugin-tcombfunction sum(a: number, b: number) { return a + b;}
const Person = t.struct({ name: t.String, // required string surname: t.maybe(t.String), // optional string age: t.Integer, // required integer tags: t.list(t.String) // a list of strings}, 'Person');// methods are defined as usualPerson.prototype.getFullName = function () { return `${this.name} ${this.surname}`;};const person = Person({ surname: 'Canti'}); // throws '[tcomb] Invalid value undefined supplied to Person/name: String'
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:
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 information stored in your types (in the meta static member). See The meta object in the docs for details.
You can customize the behavior when an assert fails leveraging the power of Chrome DevTools.
// use the default...t.fail = function fail(message) { throw new TypeError('[tcomb] ' + message); // set "Pause on exceptions" on the "Sources" panel for a great DX};// .. or define your own behaviort.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); // => 'a number'
Babel plugin
Using babel-plugin-tcomb you can also write (Flow compatible) type annotations:
function sum(a: number, b: number): number { return a + b;}