Flow

Developed and maintained by Facebook (Meta), Flow is a static type checker for JavaScript. It is meant to support React. Flow remains heavily used inside Meta itself, but has become a niche choice for the broader community; nearly all new React projects use TypeScript instead (see the next section). Flow is covered here mainly for reading legacy codebases that still use it.

To install Flow:

Installing Flow
npm install --save-dev flow-bin flow-remove-types

Add to 'package.json':


{
  "scripts": {
    "flow": "flow",
    "build": "flow-remove-types -d lib/ src/"
  }
}

Then initialize Flow:

Initializing Flow
npm run flow init

If your project was set up using Create React App (now deprecated) or another toolchain with built-in Flow support, the Flow annotations are already being stripped by default so you don't need to do anything else. To start the Flow server, which checks for changes in .js files with the //@flow annotation in the current directory and its subdirectories:

Starting the Flow server
npm run flow

To stop the server:

Stopping the Flow server
npm run flow stop

To strip the type annotations from these Flow .js files:

Stripping Flow type annotations
npm run flow build

An explanation of all the possible Flow syntaxes is beyond the scope of this tutorial:


type GreetingProps = { name: string };

function Greeting({ name }: GreetingProps) {
  return (<div>{name}</div>);
}

Using data flow analysis, Flow automatically infers types and tracks data as it moves through your code. You don't need to fully annotate your code before Flow can start to find bugs:


// @flow
function square(n) {
  return n * n; // Error!
}
square("2");