Open gcanti opened 8 years ago
Dude! Not sure how to say this, but I love you. It's been awesome getting this flow experience into my projects. I've installed the ide-flow
atom plugin and I get autocomplete and type information displayed in my IDE now! No words for how sick this is.
You are a thorough legend.
@ctrlplusb Welcome to @gcanti fan club. You are not the only one! I want to buy this man a beer. 🍺
Goal
The goal of this series of posts is to show how you can add type safety, both statically and at runtime, to your untyped codebase gradually and with a gentle migration path.
I will use the following tools:
Flow
type annotations to correspondingtcomb
models and asserts.Why?
Runtime type checking (tcomb)
Flow
tcomb
's typesStatic type checking (Flow)
babel-plugin-tcomb
isFlow
compatible, this means that you can run them side by side, statically checking your code withFlow
and lettcomb
catching the remaining bugs at runtime.Gentle migration path
You can add type safety to your untyped codebase gradually:
tcomb
Flow
and unleash the power of static type checkingSetup
First, install via npm:
Then, in your babel configuration (usually in your
.babelrc
file), add (at least) the following plugins:If you are using the
react
preset, thebabel-plugin-syntax-flow
andbabel-plugin-transform-flow-strip-types
plugins are already included:You can download
Flow
from here.Get started
Say you have this untyped function:
Adding type annotations is easy, just add a colon and a type after each parameter:
For a quick reference on type annotations, start here.
Type annotations are not valid JavaScript, but they will be stripped out by
babel-plugin-transform-flow-strip-types
so your code will run as before.Now let's introduce intentionally a bug:
Note that you can inspect the stack in order to find where the error was originated. The power of Chrome Dev Tools (or equivalent) are at your disposal.
Runnning
Flow
In order to run
Flow
, just add a.flowconfig
file to your project and a comment:at the beginning of the file. Then run
flow
from you command line. Here's the output:Types
You are not limited to primitive types, this is a annotated function which works on every object that owns a
name
and asurname
property:All the
Flow
type annotations are supported.Immutability
Immutability is enforced by
tcomb
at runtime. The values passed "through" a type annotation will be immutables:Next post
In the next post I'll talk about how to tighten up your types with the help of refinements.
Note. If you are interested in the next posts, watch this repo, I'll open a new issue for each of them when they are ready.