Socket
Socket
Sign inDemoInstall

tcomb

Package Overview
Dependencies
Maintainers
1
Versions
74
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

tcomb


Version published
Maintainers
1
Created

Package description

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

Changelog

Source

v2.2.1

  • Experimental
    • pattern matching #121

Readme

Source

build status dependency status npm downloads Join the chat at https://gitter.im/gcanti/tcomb

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.

"Si vis pacem, para bellum" - (Vegetius 5th century)

Code example

var t = require('tcomb');

// a user defined type
var Integer = t.subtype(t.Number, function (n) => { return n % 1 === 0; });

// a struct
var Person = t.struct({
  name: t.String,              // required string
  surname: t.maybe(t.String),  // optional string
  age: Integer,                // required integer
  tags: t.list(t.String)       // a list of strings
});

// methods are defined as usual
Person.prototype.getFullName = function () {
  return `${this.name} ${this.surname}`;
};

// an instance of Person (the keyword new is optional)
var person = new Person({
  name: 'Giulio',
  surname: 'Canti',
  age: 41,
  tags: ['js developer', 'rock climber']
});

Features

Lightweight

3KB gzipped.

Domain Driven Design

Write complex domain models in a breeze and with a small code footprint. Supported types:

  • user defined types
  • structs
  • lists
  • enums
  • subtypes
  • unions
  • intersections
  • the option type
  • tuples
  • dictionaries
  • functions

Based on set theory

Blog posts:

Type safety

All models are type checked:

var person = new Person({
  name: 'Giulio',
  // missing required field "age"
  tags: ['js developer', 'rock climber']
});

Output to console:

[tcomb] Invalid argument value = undefined supplied to irreducible type Number

See "Debugging with Chrome DevTools" section for details.

Immutability and immutability helpers

Instances are immutables 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:

var person2 = Person.update(person, {
  name: {$set: 'Guido'}
});

where spec is an object contaning commands. The following commands are compatible with the Facebook Immutability Helpers:

  • $push
  • $unshift
  • $splice
  • $set
  • $apply
  • $merge

See Updating immutable instances in the docs 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).

Debugging with Chrome DevTools

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
};

// .. or define your own behavior
t.fail = function fail(message) {
  debugger; // starts the Chrome DevTools debugger
  throw new TypeError(message);
};

Runtime type introspection

All models are inspectable at runtime. You can read and reuse the informations stored in your types (in a meta static property). 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.

Pattern matching

// this example uses ES6 syntax

const result = t.match(1,
  t.String, () => 'a string',
  t.Number, () => 'a number'
);

console.log(result); // => 'a number'

Docs

GUIDE.md

Contributors

Similar projects

License

The MIT License (MIT)

Keywords

FAQs

Last updated on 23 Aug 2015

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc