I’m interested in the possibility of running type checks on Javascript code.
Proponents of type checking believe that bugs can be avoided by indicating the intended type (i.e. String, Number) of values (variables, functions and classes), opponents say it adds work but doesn’t significantly reduce bugginess.
I read through the intro to Typescript and it certainly seems like a lot of work.
An alternative is Facebook’s flow, it allows gradual typing - you add only as many type annotations as you want. Here, I’m giving it a spin by creating flow-hello - a “Hello World!” Example.
Installation
The type checking system is written in OCaml, and you need to install a binary or compile from source.
I opted to use npm
to install the binary globally:
1
|
|
Project setup
Configure flow:
1
|
|
A Bug
Here’s a Javascript with a bug:
1 2 3 4 5 6 |
|
This code logs undefined
when the number 1
is passed to the function
logLength
, as 1
does not have a length
attribute:
1 2 3 |
|
As is, flow does not analyze the file:
1 2 |
|
Activate flow
Flow is activated by adding @flow
to the first comment in any file:
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 6 7 8 |
|
That’s good, as it explains how we get undefined
in the output, but it’s not
clear that this happens due to the second invocation of the function.
Annotate function parameters
Now, let’s indicate the intended type of the x
parameter so that calls with
parameters of the wrong type will be pointed out.
1 2 3 4 5 6 7 |
|
As flow check
checks all the .js
files it finds, I’ll run pass the file
contents to flow via stdin:
1 2 3 4 5 6 7 8 9 10 |
|
That’s good - we know which call caused the problem.
Stripping type annotations with Babel
Unfortunately, we can no longer simply run the code:
1 2 3 4 5 |
|
We can use Babel to remove type annotations when we want to run the code.
Setting up Babel requires a bit of work:
1 2 3 4 5 |
|
1 2 3 4 |
|
1 2 3 |
|
Now we can run babel:
1 2 3 4 5 6 7 8 |
|
We get normal Javascript as output.
Conclusion
So, I got what I wanted: help with figuring out an error cuased by calling a function with a parameter of the wrong type.
But, it’s truly a “Hello World!”, there is a whole type specification system yet to learn and try out.
I like the idea of being able to annotate just as much of my code as I like, so I think I’ll be using Flow on my next Javascript project.