• This repository has been archived on 16/Feb/2021
  • Stars
    star
    482
  • Rank 91,212 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated about 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Babel plugin for static and runtime type checking using Flow and tcomb

Babel plugin for static and runtime type checking using Flow and tcomb.

Tools

Flow is a static type checker for JavaScript.

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.

Why?

Runtime type checking (tcomb)

  • you don't want or you can't use Flow
  • you want refinement types
  • you want to validate the IO boundary (for example API payloads)
  • you want to enforce immutability
  • you want to leverage the runtime type introspection provided by tcomb's types

Static type checking (Flow)

babel-plugin-tcomb is Flow compatible, this means that you can run them side by side, statically checking your code with Flow and let tcomb catching the remaining bugs at runtime.

Gentle migration path

You can add type safety to your untyped codebase gradually:

  • first, add type annotations where you think they are most useful, file by file, leveraging the runtime type safety provided by tcomb
  • then, when you feel comfortable, turn on Flow and unleash the power of static type checking
  • third, for even more type safety, define your refinement types and validate the IO boundary

Fork

Here you can find a fork of this plugin that provides the following additional features:

  • Avoid checks on confident assignment
  • Bounded polymorphism partial support
  • let checks
  • Assignment type checking

Setup

First, install via npm.

npm install --save-dev tcomb
npm install --save-dev babel-plugin-tcomb

Then, in your babel configuration (usually in your .babelrc file), add (at least) the following plugins:

{
  "plugins" : [
    "syntax-flow",
    "tcomb",
    "transform-flow-strip-types"
  ]
}

Note. syntax-flow and transform-flow-strip-types are already included with the React Preset.

Note. Use Babel's env option to only use this plugin in development.

Warning. If you use multiple presets and are experiencing issues, try tweaking the preset order and setting passPerPreset: true. Related issues: #78 #99

Important. tcomb must be requireable

Plugin configuration

skipAsserts?: boolean = false

Removes the asserts and keeps the domain models

warnOnFailure?: boolean = false

Warns (console.warn) about type mismatch instead of throwing an error

globals?: Array<Object>

With this option you can handle global types, like Class or react SyntheticEvent

Example

"plugins" : [
  ["tcomb", {
    globals: [
      // flow
      {
        'Class': true
      }
      // react
      {
        'SyntheticEvent': true,
        ...
      },
      // your custom global types (if any)
      ...
    ]
  }],
]

Definition files

Definition files for tcomb and tcomb-react are temporarily published here.

Caveats

  • tcomb must be requireable
  • type parameters (aka generics) are not handled (Flow's responsibility)

How it works

First, add type annotations.

// index.js

function sum(a: number, b: number) {
  return a + b
}

sum(1, 'a') // <= typo

Then run Flow (static type checking):

index.js:7
  7: sum(1, 'a')
     ^^^^^^^^^^^ function call
  7: sum(1, 'a')
            ^^^ string. This type is incompatible with
  3: function sum(a: number, b: number) {
                                ^^^^^^ number

or refresh your browser and look at the console (runtime type checking):

Uncaught TypeError: [tcomb] Invalid value "a" supplied to b: Number

Domain models

// index.js

type Person = {
  name: string, // required string
  surname?: string, // optional string
  age: number,
  tags: Array<string>
};

function getFullName(person: Person) {
  return `${person.name} ${person.surname}`
}

getFullName({ surname: 'Canti' })

Flow:

index.js:14
 14: getFullName({
     ^ function call
 10: function getFullName(person: Person) {
                                  ^^^^^^ property `name`. Property not found in
 14: getFullName({
                 ^ object literal

tcomb:

TypeError: [tcomb] Invalid value undefined supplied to person: Person/name: String

Refinements

In order to define refinement types you can use the $Refinement type, providing a predicate identifier:

import type { $Refinement } from 'tcomb'

// define your predicate...
const isInteger = n => n % 1 === 0

// ...and pass it to the suitable intersection type
type Integer = number & $Refinement<typeof isInteger>;

function foo(n: Integer) {
  return n
}

foo(2)   // flow ok, tcomb ok
foo(2.1) // flow ok, tcomb throws [tcomb] Invalid value 2.1 supplied to n: Integer
foo('a') // flow throws, tcomb throws

In order to enable this feature add the tcomb definition file to the [libs] section of your .flowconfig.

Runtime type introspection

Check out the meta object in the tcomb documentation.

import type { $Reify } from 'tcomb'

type Person = { name: string };

const ReifiedPerson = (({}: any): $Reify<Person>)
console.log(ReifiedPerson.meta) // => { kind: 'interface', props: ... }

In order to enable this feature add the tcomb definition file to the [libs] section of your .flowconfig.

Validating (at runtime) the IO boundary using typecasts

type User = { name: string };

export function loadUser(userId: string): Promise<User> {
  return axios.get('...').then(p => (p: User)) // <= type cast
}

Recursive types

Just add a // recursive comment on top:

// recursive
type Path = {
  node: Node,
  parentPath: Path
};

Type-checking Redux

import { createStore } from 'redux'

// types
type State = number;
type ReduxInitAction = { type: '@@redux/INIT' };
type Action = ReduxInitAction
  | { type: 'INCREMENT', delta: number }
  | { type: 'DECREMENT', delta: number };

function reducer(state: State = 0, action: Action): State {
  switch(action.type) {
    case 'INCREMENT' :
      return state + action.delta
    case 'DECREMENT' :
      return state - action.delta
  }
  return state
}

type Store = {
  dispatch: (action: Action) => any;
};

const store: Store = createStore(reducer)

store.dispatch({ type: 'INCREMEN', delta: 1 }) // <= typo

// throws [tcomb] Invalid value { "type": "INCREMEN", "delta": 1 } supplied to action: Action
// Flow throws as well

Type-checking React using tcomb-react

See tcomb-react:

// @flow

import React from 'react'
import ReactDOM from 'react-dom'
import { props } from 'tcomb-react'

type Props = {
  name: string
};

@props(Props)
class Hello extends React.Component<void, Props, void> {
  render() {
    return <div>Hello {this.props.name}</div>
  }
}


ReactDOM.render(<Hello />, document.getElementById('app'))

Flow will throw:

index.js:12
 12: class Hello extends React.Component<void, Props, void> {
                                               ^^^^^ property `name`. Property not found in
 19: ReactDOM.render(<Hello />, document.getElementById('app'))
                     ^^^^^^^^^ props of React element `Hello`

while tcomb-react will warn:

Warning: Failed propType: [tcomb] Invalid prop "name" supplied to Hello, should be a String.

Detected errors (1):

  1. Invalid value undefined supplied to String

Additional babel configuration:

{
  "presets": ["react", "es2015"],
  "passPerPreset": true,
  "plugins" : [
    "tcomb",
    "transform-decorators-legacy"
  ]
}

In order to enable this feature add the tcomb-react definition file to the [libs] section of your .flowconfig. Also you may want to set esproposal.decorators=ignore in the [options] section of your .flowconfig.

Without decorators

// @flow

import React from 'react'
import ReactDOM from 'react-dom'
import { propTypes } from 'tcomb-react'
import type { $Reify } from 'tcomb'

type Props = {
  name: string
};

class Hello extends React.Component<void, Props, void> {
  render() {
    return <div>Hello {this.props.name}</div>
  }
}

Hello.propTypes = propTypes((({}: any): $Reify<Props>))

ReactDOM.render(<Hello />, document.getElementById('app'))

Under the hood

Primitives

type MyString = string;
type MyNumber = number;
type MyBoolean = boolean;
type MyVoid = void;
type MyNull = null;

compiles to

import _t from "tcomb";

const MyString = _t.String;
const MyNumber = _t.Number;
const MyBoolean = _t.Boolean;
const MyVoid = _t.Nil;
const MyNull = _t.Nil;

Consts

const x: number = 1

compiles to

const x = _assert(x, _t.Number, "x");

Note: lets are not supported.

Functions

function sum(a: number, b: number): number {
  return a + b
}

compiles to

import _t from "tcomb";

function sum(a, b) {
  _assert(a, _t.Number, "a");
  _assert(b, _t.Number, "b");

  const ret = function (a, b) {
    return a + b;
  }.call(this, a, b);

  _assert(ret, _t.Number, "return value");
  return ret;
}

where _assert is an helper function injected by babel-plugin-tcomb.

Type aliases

type Person = {
  name: string,
  surname: ?string,
  age: number,
  tags: Array<string>
};

compiles to

import _t from "tcomb";

const Person = _t.interface({
  name: _t.String,
  surname: _t.maybe(_t.String),
  age: _t.Number,
  tags: _t.list(_t.String)
}, "Person");

More Repositories

1

fp-ts

Functional programming in TypeScript
TypeScript
10,811
star
2

io-ts

Runtime type system for IO decoding/encoding
TypeScript
6,694
star
3

tcomb-form-native

Forms library for react-native
JavaScript
3,148
star
4

tcomb

Type checking and DDD for JavaScript
JavaScript
1,897
star
5

tcomb-form

Forms library for react
JavaScript
1,163
star
6

monocle-ts

Functional optics: a (partial) porting of Scala monocle
TypeScript
1,001
star
7

newtype-ts

Implementation of newtypes in TypeScript
TypeScript
553
star
8

flow-static-land

[DEPRECATED, please check out fp-ts] Implementation of common algebraic types in JavaScript + Flow
JavaScript
408
star
9

functional-programming

Introduction to Functional Programming (Italian)
TypeScript
401
star
10

tcomb-validation

Validation library based on type combinators
JavaScript
400
star
11

typelevel-ts

Type level programming in TypeScript
TypeScript
354
star
12

io-ts-types

A collection of codecs and combinators for use with io-ts
TypeScript
311
star
13

elm-ts

A porting to TypeScript featuring fp-ts, rxjs6 and React
TypeScript
301
star
14

redux-tcomb

Immutable and type-checked state and actions for Redux
JavaScript
211
star
15

tcomb-react

Alternative syntax for PropTypes
JavaScript
202
star
16

fp-ts-contrib

A community driven utility package for fp-ts
TypeScript
199
star
17

parser-ts

String parser combinators for TypeScript
TypeScript
194
star
18

fp-ts-rxjs

fp-ts bindings for RxJS
TypeScript
188
star
19

prop-types-ts

Alternative syntax for prop types providing both static and runtime type safety, powered by io-ts
TypeScript
170
star
20

fp-ts-routing

A type-safe bidirectional routing library for TypeScript
TypeScript
168
star
21

retry-ts

Retry combinators for monadic actions that may fail
TypeScript
162
star
22

io-ts-codegen

Code generation for io-ts
TypeScript
152
star
23

tcomb-json-schema

Transforms a JSON Schema to a tcomb type
JavaScript
144
star
24

flowcheck

[DEPRECATED, use babel-plugin-tcomb instead] Runtime type checking for Flow
JavaScript
116
star
25

fp-ts-codegen

TypeScript code generation from a haskell-like syntax for ADT. Playground:
TypeScript
101
star
26

docs-ts

A zero-config documentation tool for my TypeScript projects
TypeScript
100
star
27

logging-ts

Composable loggers for TypeScript
TypeScript
99
star
28

flowcheck-loader

[DEPRECATED] A Webpack loader for Flowcheck
JavaScript
89
star
29

tom

Elmish type-safe state and side effect manager using RxJS
JavaScript
87
star
30

money-ts

TypeScript library for type-safe and lossless encoding and manipulation of world currencies and precious metals
TypeScript
87
star
31

fp-ts-laws

fp-ts type class laws for property based testing
TypeScript
80
star
32

flow-io

[DEPRECATED, please check out io-ts] Flow compatible runtime type system for IO validation
JavaScript
73
star
33

react-vdom

Pulls out the VDOM and makes tests easy (also in node and without the DOM)
JavaScript
72
star
34

uvdom

Universal Virtual DOM
JavaScript
53
star
35

fp-ts-fluture

fp-ts bindings for Fluture
TypeScript
50
star
36

fp-ts-local-storage

fp-ts bindings for LocalStorage
TypeScript
49
star
37

graphics-ts

A porting of purescript-{canvas, drawing} featuring fp-ts
TypeScript
44
star
38

tcomb-react-bootstrap

Type checking for react-bootstrap [DEPRECATED]
JavaScript
41
star
39

talks

talks and blog posts
HTML
41
star
40

unknown-ts

A polyfill of unknown that works with legacy typescript versions (before 3.0)
TypeScript
28
star
41

mtl-ts

MTL-style in TypeScript
TypeScript
24
star
42

recursion-schemes-ts

Recursion schemes in TypeScript (POC)
TypeScript
22
star
43

tcomb-doc

Documentation tool for tcomb
JavaScript
14
star
44

babel-plugin-tcomb-boilerplate

Boilerplate showing what you can get in terms of type safety with babel-plugin-tcomb
JavaScript
14
star
45

fp-ts-node

TypeScript
13
star
46

flow-react

Advanced type checking for react using Flow
JavaScript
13
star
47

pantarei

Repository for idiomatic Flowtype definition files
JavaScript
11
star
48

elm-ts-todomvc

todomvc implementation using elm-ts and fp-ts
TypeScript
11
star
49

typescript-course

Esercizi del corso di programmazione avanzata con TypeScript
TeX
11
star
50

tcomb-form-templates-semantic

Semantic UI templates for tcomb-form
JavaScript
11
star
51

tcomb-form-templates-bootstrap

Bootstrap templates for tcomb-form
JavaScript
10
star
52

sanctuary-libdef

Flow definition file for sanctuary
JavaScript
9
star
53

simple-date-picker

A simple clean way to pick dates with React
JavaScript
9
star
54

flow-update

Statically type checked model updates using Flow
JavaScript
8
star
55

profunctor-lenses-ts

Pure profunctor lenses in TypeScript (just a POC)
TypeScript
8
star
56

fp-typed-install

TypeScript
7
star
57

cerebral-tcomb

[No Maintenance Intended] immutable and type checked model layer for cerebral
JavaScript
7
star
58

import-path-rewrite

JavaScript
6
star
59

fractal-trees-ts

Fractal trees with fp-ts
TypeScript
6
star
60

fcomb

Function combinators
JavaScript
5
star
61

uvdom-bootstrap

Bootstrap 3 components built with uvdom
JavaScript
5
star
62

simple-format-number

A simple clean way to format numbers with Javascript
JavaScript
5
star
63

behaviors-ts

A porting of purescript-behaviors
TypeScript
5
star
64

tree-shaking-test

JavaScript
4
star
65

io-ts-benchmarks

TypeScript
3
star
66

fetch-optimizer

[No Maintenance Intended] Optimises dependent data fetchers
JavaScript
2
star
67

simple-format-timeago

A simple clean way to format intervals with Javascript
JavaScript
2
star
68

simple-format-date

A simple clean way to format dates with Javascript
JavaScript
2
star
69

tcomb-i18n

Simple i18n / i17n helpers [DEPRECATED]
JavaScript
2
star
70

simple-parse-number

A simple clean way to parse numbers with Javascript
JavaScript
1
star