posts by Jesse Hallett

Flow Cookbook: Flow & React

Last updated 2017-01-07

This recipe is part of the Flow Cookbook series.

Flow and React are both Facebook projects - so as you might imagine, they work quite well together. React components can take type parameters to specify types for props, default props, and state. Type-checking works well with both functional and class components.

Flow type annotations provide an alternative to propTypes runtime checks. Flow’s static checking has some advantages:

  • Problems are reported immediately - it is not necessary to run tests that evaluate every component to identify props mismatches.
  • Flow types can be more precise and concise than propTypes.
  • Flow can also check state as well as props.
  • In addition to checking that a component gets the correct props, Flow checks that props and states are used correctly within the component’s render method, and in other component methods.

Flow Cookbook: Unpacking JSON API data

This recipe is part of the Flow Cookbook series.

Hacker News provides a public API. One of the endpoints of that API accepts an ID and responds with an item:


Here is an example of a response:

  "by" : "todd8",
  "dead" : true,
  "id" : 13225417,
  "score" : 1,
  "time" : 1482277147,
  "title" : "U.S. Department of Energy Misconduct [pdf]",
  "type" : "story",
  "url" : ""

An “item” might be a story, a comment, a question, a job posting, a poll, or a voting option in a poll. Each item type has different properties - for example stories have a title, but comments do not. If you don’t have context for the ID, the only way to know what you have fetched is to check the type property of the response at runtime. To add type safety to a call to this API, it is necessary to describe a type that encompasses all of the possible shapes that the returned data might take. That is going to be a union type, which will look something like this:

Flow Cookbook

Last updated 2017-01-07

Type-checking can be a useful asset in a Javascript project. A type checker can catch problems that are introduced when adding features or refactoring, which can reduce the amount of time spent debugging and testing. Type annotations provide a form of always-up-to-date documentation that makes it easier for developers to understand an unfamiliar code base. But it is important to use type-checking effectively to get its full benefit.

The Javascript community is fortunate to have a choice of two great type checkers. These recipes focus on Flow, and introduce patterns for using Flow effectively.

Advanced features in Flow

Flow has some very interesting features that are currently not documented. It is likely that the reason for missing documentation is that these features are still experimental. Caveat emptor.

I took a stroll through the source code for Flow v0.11. Here is what I found while reading and react.js.

Flow is the JavaScript type checker I have been waiting for

I am very excited about Flow, a new JavaScript type checker from Facebook. I have put some thought into what a type checker for JavaScript should do - and in my opinion Facebook gets it right. The designers of Flow took great effort to make it work well with JavaScript idioms, and with off-the-shelf JavaScript code. The key features that make that possible are type inference and path-sensitive analysis. I think that Flow has the potential to enable sweeping improvements to the code quality of countless web apps and Node apps.

From the announcement post:

…underlying the design of Flow is the assumption that most JavaScript code is implicitly statically typed; even though types may not appear anywhere in the code, they are in the developer’s mind as a way to reason about the correctness of the code. Flow infers those types automatically wherever possible, which means that it can find type errors without needing any changes to the code at all.

This makes Flow fundamentally different than existing JavaScript type systems (such as TypeScript), which make the weaker assumption that most JavaScript code is dynamically typed, and that it is up to the developer to express which code may be amenable to static typing.

Path-sensitive analysis means that Flow reads control flow to narrow types where appropriate.

Javascript generators and functional reactive programming

tl;dr: ECMAScript 6 introduces a language feature called generators, which are really great for working with asynchronous code that uses promises. But they do not work well for functional reactive programming.

ES6 generators allow asynchronous code to be written in a way that looks synchronous. This example uses a hypothetical library called Do (implementation below) that makes promises work with generators:

var postWithAuthor = Do(function*(id) {
    var post   = yield getJSON('/posts/'+id)
    var author = yield getJSON('/users/'+post.authorId)
    return _.assign(post, { author: author })

Do(function*() {
    var post = yield postWithAuthor(3)
    console.log('Post written by',

It is possible to use generators now in Node.js version 0.11 by using the --harmony flag. Or you can use Traceur to transpile ES6 code with generators into code that can be run in any ES5-compatible web browser.

Kinesis Advantage with DSA keycaps

I now have a Kinesis Advantage keyboard for use at work. I have been feeling some wrist strain recently; and some of my coworkers were encouraging me to try one. So I borrowed a Kinesis for a week, and found that I really liked it. The contoured shape makes reaching for keys comfortable; I find the column layout to be nicer than the usual staggered key arrangement; and between the thumb-key clusters and the arrow keys, there are a lot of options for mapping modifier keys that are in easy reach.

Kinesis Advantage, before modification

But I really like the PBT keycaps on my Leopold. I would not enjoy going back to plain, old ABS. I also don’t want my keyboard to be just like every other Kinesis. So I decided to get replacement keycaps.

Category Theory proofs in Idris

Idris is a programming language with dependent types. It is similar to Agda, but hews more closely to Haskell. The goal of Idris is to bring dependent types to general-purpose programming. It supports multiple compilation targets, including C and Javascript.

Dependent types provide an unprecedented level of type safety. A quick example is a type-safe printf implementation (video). They are also useful for theorem proving. According to the Curry-Howard correspondence, mathematical propositions can be represented in a program as types. An implementation that satisfies a given type serves as a proof of the corresponding proposition. In other words, inhabited types represent true propositions.

The Curry-Howard correspondence applies to every language with type checking. But the type systems in most languages are not expressive enough to build very interesting propositions. On the other hand, dependent types can express quantification (i.e., the mathematical concepts of universal quantification (∀) and existential quantification (∃)). This makes it possible to translate a lot of interesting math into machine-verified code.

Functional data structures in JavaScript with Mori

I have a long-standing desire for a JavaScript library that provides good implementations of functional data structures. Recently I found Mori, and I think that it may be just the library that I have been looking for. Mori packages data structures from the Clojure standard library for use in JavaScript code.

Functional data structures

A functional data structure (also called a persistent data structure) has two important qualities: it is immutable and it can be updated by creating a copy with modifications (copy-on-write). Creating copies should be nearly as cheap as modifying a comparable mutable data structure in place. This is achieved with structural sharing: pointers to unchanged portions of a structure are shared between copies so that memory need only be allocated for changed portions of the data structure.

A simple example is a linked list. A linked list is an object, specifically a list node, with a value and a pointer to the next list node, which points to the next list node. (Eventually you get to the end of the list where there is a node that points to the empty list.) Prepending an element to the front of such a list is a constant-time operation: you just create a new list element with a pointer to the start of the existing list. When lists are immutable there is no need to actually copy the original list. Removing an element from the front of a list is also a constant-time operation: you just return a pointer to the second element of the list. Here is a slightly more-detailed explanation.

Lists are just one example. There are functional implementations of maps, sets, and other types of structures.

Rich Hickey, the creator Clojure, describes functional data structures as decoupling state and time. (Also available in video form.) The idea is that code that uses functional data structures is easier to reason about and to verify than code that uses mutable data structures.