flow

Adds static typing to JavaScript to improve developer productivity and code quality.

Subscribe to updates I use flow


Statistics on flow

Number of watchers on Github 15700
Number of open issues 2083
Average time to close an issue 1 day
Main language OCaml
Average time to merge a PR about 16 hours
Open pull requests 264+
Closed pull requests 508+
Last commit 6 months ago
Repo Created almost 4 years ago
Repo Last Updated 6 months ago
Size 35.1 MB
Homepage https://flow.org/
Organization / Authorfacebook
Latest Releasev0.67.1
Contributors130
Page Updated
Do you use flow? Leave a review!
View open issues (2083)
View flow activity
View TODOs for flow (132)
View on github
Latest Open Source Launches
Trendy new open source projects in your inbox! View examples

Subscribe to our mailing list

Evaluating flow for your project? Score Explanation
Commits Score (?)
Issues & PR Score (?)

Flow Build Status Windows Build Status

Flow is a static typechecker for JavaScript. To find out more about Flow, check out flow.org.

For a background on the project, please read this overview.

Requirements

Flow works with:

  • Mac OS X
  • Linux (64-bit)
  • Windows (64-bit)

There are binary distributions for each of these platforms and you can also build it from source on any of them as well.

Installing Flow

Flow is simple to install: all you need is the flow binary on your PATH and you're good to go.

Installing Flow Per Project

The recommended way to install Flow is via the flow-bin npm package. Adding flow-bin to your project's package.json:

  • provides a smoother upgrade experience, since the correct version of Flow is automatically used based on the revision you check out
  • installs Flow as part of your existing npm install workflow
  • lets you use different versions of Flow on different projects
npm install --save-dev flow-bin
node_modules/.bin/flow

Installing Flow Globally

Although not recommended, you can also install Flow globally (for example, perhaps you don't use npm or package.json).

The best way to install globally is via flow-bin:

npm install -g flow-bin
flow # make sure `npm bin -g` is on your path

On Mac OS X, you can install Flow via the Homebrew package manager:

brew update
brew install flow

You can also build and install Flow via the OCaml OPAM package manager. Since Flow has some non-OCaml dependencies, you need to use the depext package like so:

opam install depext
opam depext --install flowtype

If you don't have a new enough version of OCaml to compile Flow, you can also use OPAM to bootstrap a modern version. Install OPAM via the binary packages for your operating system and run:

opam init --comp=4.03.0
opam install flowtype
eval `opam config env`
flow --help

Getting started

Getting started with flow is super easy.

  • Initialize Flow by running the following command in the root of your project

    flow init
    
  • Add the following to the top of all the files you want to typecheck

    /* @flow */
    
  • Run and see the magic happen

    flow check
    

More thorough documentation and many examples can be found at https://flow.org.

Building Flow

Flow is written in OCaml (OCaml 4.03.0 or higher is required). You can install OCaml on Mac OS X and Linux by following the instructions at ocaml.org.

For example, on Ubuntu 16.04 and similar systems:

sudo apt-get install opam
opam init --comp 4.03.0

On OS X, using the brew package manager:

brew install opam
opam init --comp 4.03.0

Then, restart your shell and install these additional libraries:

opam update
opam pin add flowtype . -n
opam install --deps-only flowtype

Once you have these dependencies, building Flow just requires running

make

This produces a bin folder containing the flow binary.

In order to make the flow.js file, you first need to install js_of_ocaml:

opam install -y js_of_ocaml

After that, making flow.js is easy:

make js

The new flow.js file will also live in the bin folder.

Note: at this time, the OCaml dependency prevents us from adding Flow to npm. Try flow-bin if you need a npm binary wrapper.

Flow can also compile its parser to JavaScript. Read how here.

Building Flow on Windows

This is a little more complicated. Here is a process that works, though it probably can be simplified.

The general idea is that we build in Cygwin, targeting mingw. This gives us a binary that works even outside of Cygwin.

Install Cygwin

  1. Install Cygwin 64bit from https://cygwin.com/install.html
  2. In powershell, run iex ((new-object net.webclient).DownloadString("https://raw.githubusercontent.com/ocaml/ocaml-ci-scripts/master/appveyor-install.ps1")) which will likely run a cygwin setup installer with a bunch of cygwin packages and stuff. This helps make sure that every package that opam needs is available.

Install Opam

  1. Open the cygwin64 terminal
  2. Download opam with curl -fsSL -o opam64.tar.xz https://github.com/fdopen/opam-repository-mingw/releases/download/0.0.0.1/opam64.tar.xz
  3. tar -xf opam64.tar.xz
  4. cd opam64
  5. Install opam ./install.sh
  6. Initialize opam to point to a mingw fork: opam init -a default "https://github.com/fdopen/opam-repository-mingw.git" --comp "4.03.0+mingw64c" --switch "4.03.0+mingw64c"
  7. Make sure opam stuff is in your path: eval `opam config env`

Install Flow

  1. Clone flow: git clone https://github.com/facebook/flow.git
  2. cd flow
  3. Tell opam to use this directory as the flowtype project: opam pin add flowtype . -n
  4. Install system dependencies opam depext -u flowtype
  5. Install Flow's dependencies opam install flowtype --deps-only
  6. We need these too: opam install camlp4 ocp-build
  7. Finally, build Flow: make all-ocp

Using Flow's parser from JavaScript

While Flow is written in OCaml, its parser is available as a compiled-to-JavaScript module published to npm, named flow-parser. Most end users of Flow will not need to use this parser directly (and should install flow-bin from npm above), but JavaScript packages which make use of parsing Flow-typed JavaScript can use this to generate Flow's syntax tree with annotated types attached.

Running the tests

To run the tests, first compile flow using make. Then run bash ./runtests.sh bin/flow

There is a make test target that compiles and runs tests.

To run a subset of the tests you can pass a second argument to the runtests.sh file.

For example: bash runtests.sh bin/flow class | grep -v 'SKIP'

Join the Flow community

License

Flow is MIT-licensed (LICENSE). The website and documentation are licensed under the Creative Commons Attribution 4.0 license (website/LICENSE-DOCUMENTATION).

flow open issues Ask a question     (View All Issues)
  • almost 2 years is this a bug ? in switch statement ?
  • almost 2 years Flow complains about this code when it shouldn't
  • almost 2 years Flow declarations requires server restart to fix library parse errors
  • almost 2 years Spreading paramaters in functions cause error but manually indexing succeeds
  • almost 2 years flow-parser: Code generation
  • almost 2 years Flow does not support export from construction
  • almost 2 years Import failure with private modules
  • almost 2 years Unexpected $Diff behavior
  • almost 2 years `yield` should invalidate refinements
  • almost 2 years Polymorphic types crash flow with "Stack overflow" error
  • almost 2 years Node libdefs should return subtypes
  • almost 2 years Unsafe behaviour for unrecognised case in case analysis
  • almost 2 years Function Inference w/ Object Properties
  • almost 2 years Could not resolve name which customized
  • almost 2 years Unsound `typeof val === 'function'` refinement
  • almost 2 years CLI command to report files with `@flow` annotation
  • almost 2 years Disjoint union incosistency
  • almost 2 years Any way to declare getters in interface?
  • almost 2 years libs not getting included
  • almost 2 years Typed Holes + Type Wildcards?
  • almost 2 years Type check class that extends class from build in module
  • almost 2 years Class instance should not be allowed to cast to an arbitrary object type.
  • almost 2 years Class type gets bugged in certain cases unless constructor return type is explicitly set to void
  • almost 2 years gen-flow-files generates union type declaration that confuses importer
  • almost 2 years Recursion limit exceeds
  • almost 2 years optional attributes on object literals
  • almost 2 years ESLint collision `no-duplicate-imports`
  • almost 2 years flow doesn't follow `export * from`
  • almost 2 years getters/setters with WeakMaps for private data should not be considered unsafe?
  • almost 2 years Parser should consider `@` part of the source of a decorator node
flow open pull requests (View All Pulls)
  • Improve definitions for `Symbol`.
  • Allow `crossOrigin` to be nullable for HTMLImageElement, and HTMLMediaElement.
  • Adding whatwg fetch
  • Remove extraneous type param on Promise
  • [RFC] `flow-lib`: JS interfaces for Flow APIs
  • fix mistakes in code examples
  • Fix the code example in the Objects / Adding Properties (#1344)
  • Add Object.setPrototypeOf definition
  • DOM Traversal, Take 2
  • add section about mixins for declared classes in docs
  • Add type definitions for Object.entries and Object.values
  • Adding KeyboardEvents to EventTarget
  • Use opam on OS X in travis
  • typing custom element lifecycle callbacks
  • changing vars to ES6 const (and let)
  • Fix `float_of_string` on Windows.
  • Restore state on slave after the fork/exec.
  • Handling some timeout on windows
  • Add missing declarations to builtins.
  • Fun time with ocamldoc
  • Test proptypes typecheck across module boundaries
  • Add failing test for class-level esproposal_decorators
  • Attempt to show Flow rules firing with a GIF.
  • Add `getSelection` method to Document class and add Selection class
  • Documentation: add example
  • Adding Error.captureStackTrace
  • DOM scrollIntoView(): Allow passing of object
  • Add declarations for ReactDOM.unstable_*
  • Add support for flow prefixes in package.json keys
  • Add missing OCaml C runtime macros, occasional style changes as well
  • Add Object.values to lib declaration
  • Using booleans in filter&co. callbacks
  • Fix false negative arising from generics and addition
  • adding-new-attr-to-dom-lib - Adding getAttribute to the Node type
  • Add 'ls' command to list files flow can see
  • Support subtyping on Class<> qualified annotations
  • Parser Tests
  • Constant propagation for addition
  • Add spread for strings and Iterables
  • fix Element.namespaceURI property
  • Adding blog post about Facebook's F8 app
  • Added missing attributes and methods for HTMLInputElement
  • add IFrame contentWindow and contentDocument
  • Support `this` pseudo-params in classes, and enforce subtyping on structural class statics
  • add TextEncoder & TextDecoder libdefs
  • Add `CustomEvent` class declaration
  • Fixes for node's 'net', 'child_process' lib
  • Fix up the flow parser npm README
  • [parser] Allow `type` as an imported binding
  • Add missing Buffer method declarations
  • Statics subtyping
  • Class_sig refactor
  • added documentation for HOCs
  • adjust MutationRecord lib definition
  • Parser support for `declare module "foo" { declare export ... }`
  • Add getMaxListeners to node's process object.
  • Avoid frozen build when `git` or `.git/`+`hg` are unavailable
  • Introduce intersection operator in docs with object types
  • fix ocaml 4.03.0 compile
  • Update the declaration of cloneNode to use self instead of Node
  • Nullable check with class fields lost after first expression
  • Add missing assert method declarations
  • Fix typo in modules.doc.js
  • Change `MessageEvent::source` to `any`
  • Infer munged instance members.
  • [try] Store last edit in localStorage for next load
  • Add Error.stackTraceLimit and Error.prepareStackTrace.
  • node Buffer can be constructed from ArrayBuffer and Uint8Array
  • Added TouchEvent, TouchList & Touch declarations
  • Code block-ify Objects as Map
  • Timeout should raise End_of_file instead of EPIPE
  • Fix Windows process ID/HANDLE mess
  • Fix log rotating on Windows
  • Fix Tail for Windows
  • ./tool test --watch
  • Update types for input events.
  • Add some Chrome definitions
  • readme.md should be more focused on installing & usage.
  • add better type for arr.filter(Boolean)
  • add http/https ServerResponse types
  • require [version] in flowconfig
  • `flow shadow-file`
  • Update the type of OscillatorNode's type property
  • [RFC] GraphQL support
  • Add path to filesystem streams in lib/node.js
  • Add ArrayBuffer support to node Buffer
  • Fix accessing number literal properties on objects
  • Support custom promises
  • [RFC] Avoid killing Flow server on package.json changes
  • Add type declarations for web worker globals and the importScripts me…
  • Add support for iterables in Promise.all
  • Emacs plugin rewrite
  • Builtin support for requiring resource files (css, jpg, etc)
  • Declare the correct return type for Buffer#toJSON in node. Fixes #1647
  • Fixes for compatibility with OCaml 4.04
  • Fix regex in 02-advanced-configuration.md
  • Fix libdef for Array find
  • Complete node's EventEmitter API definition
  • node: child_process.execFile callback passes extended error object
  • Add setHeader to ClientRequest
  • Error by default when `import type` pulls from an untyped module
  • Typings for the Web Components spec (and other stuff)
  • Fix type declaration for require
  • Only print json if the --json flag is used with the coverage command
  • Update node.js
  • Remove the search command from cli docs. Fixes #2306
  • Add deprecated initEvent method to Event. Fixes #2336
  • Add declaration for performance global. Fixes #2345
  • Fix value of OscillatorNode.type
  • Remove hh_realpath error from /try
  • Synchronize stream.Duplex and stream.Writable definition of the end() method
  • Mark MessageEvent#data as mixed.
  • Misc DOM method type definition fixes
  • Adds a `weak` option to the .flowConfig format
  • Update types of node cluster
  • Update types in node API: child_processes
  • Add Make server.close callback more specific.
  • Update querySelector return type
  • Add stream$Writable as a mixin to stream$Duplex
  • Make parameter names in function types optional
  • Add failing test for issue
  • Add documentation for $Diff<A, B>
  • FormData definitions
  • Add documentation for $Keys<T>
  • Add AnimationEvent to DOM types
  • Overload addEventListener method of Worker.
  • Add special cases for touch and wheel events in EventTarget class
  • Complete class declaration for FormData spec
  • Added Gitter flow channel link
  • WeakMap#get can be undefined
  • Add missing ChildProcess#unref()
  • add WebGL 1.0 types
  • Fix typo and minor clarity improvements
  • fix: Node.js definitions: supply static & constructor signatures for crypto$Verify & crypto$SIgn
  • fix: add node.js crypto.Sign and crypto.Verify exports
  • [flowtype.org] use Yarn instead of npm/bower
  • Update declarations.doc.js
  • Array#pop and Array#shift should return nullables
  • GraphQL: Parser and schema loading.
  • Added DragEventTypes and support.
  • Add constructor to Set declaration
  • Make node's Buffer class extend Uint8Array
  • Add import type shorthand syntax
  • [bom] Define MutationObserverInit
  • Adds `emitKeypressEvents` to the `readline` module definition
  • Add EventListenerOptions support
  • Fix childprocess
  • First step towards GraphQL support
  • Forward abnormal-return for `while(true) { return ; }`
  • Type-preserving versions of `Object.entries`/`Object.values`
  • [docs] Update quick reference for array syntax including shorthand
  • Add declarations for Node's http.Agent
  • Fix source location for class instances.
  • Fix a typo in React example
  • Define defaultProps directly in docs
  • fix(bom): make readyStates static props of XMLHttpRequest
  • Adding WebUSB API
  • Add "dumpTypes" to flow.js
  • Add ParentNode and ChildNode pure interfaces to the appropriate types
  • HTMLOptionsCollection extends HTMLCollection
  • Add HTMLTemplateElement
  • Improve lib def for WebSocket 'close', 'message' event handlers
  • [WIP] GraphQL #2: GraphqlData, GraphqlVars, args/vars validaton
  • Update handling of JSXText to trim and filter empty text
  • [docs] Remove wrong spread operator in destructuring example.
  • [RFC] Use ocp-build + watchman for oss build.
  • Add overload for setState to support function as argument
  • Fix Element type's requestFullscreen
  • Support computed properties for instances.
  • Declare HTMLFieldSetElement
  • Fixes String#match and RegExp#exec declarations. (#2450)
  • [docs]: Documentation for Class<T>, $PropertyType<T, x>, $Exact<T>, and *
  • Allow all types as a key in `$PropertyType`.
  • [parser] use _tags to include sedlex
  • Fix inconsistency prop vs. p
  • Simplifying & Clarifying Module Docs
  • Fix errors in primitive types docs
  • [doc] Link to refinement invalidation from maybe
  • Added type definitions for Notification
  • Added OGP images.
  • Add Flow definition to `React refs` Example
  • Fix naming of optional property in example
  • Include birthtime on Stats object
  • Add method type definition for JSON.stringify with undefined input fi…
  • Subtypes of unions of functions
  • Add failing test for #3309
  • Add React context support to lib definitions
  • Add $ReadOnly<T> utility type
  • Support annotations in catch clause
  • Add declaration for node.js’ process.emitWarning
  • add covered_locs output to coverage
  • Fix autocomplete for generic type aliases
  • lib/BOM: add missing "speed" to Coordinates
  • add getContext("experimental-webgl") typecheck
  • ISSUE_TEMPLATE.md
  • Add missing property of ValidityState type
  • Make readyState constants static
  • Add native 'cluster' module method defenition
  • Add support for abstract classes
  • Publish to opam in Travis
  • Typecheck interface statics
  • [RFC] Improve core types for (Async) Iterable/Iterator/Generator
  • Fix Date locale parameter types
  • Document $Shape in types/utilities.md
  • Feature/node https agent
  • Add Node type to React definition
  • Add responseURL to XMLHttpRequest
  • Make process.umask's argument optional
  • Add documentation for $Shape<T>
  • Added JavaScript Enhancements plugin to Sublime Text 3 editor - docs
  • Add validationMessage to HTMLSelectElement
  • Fix send type
  • Fix arity of clearInterval, clearTimeout
  • update README docs about windows compatibility
  • Added Buffer swap64() to node definitions
  • fix indent
  • Add optional error type param to the Promise
  • Allow passing null or undefined to clear timer functions.
  • Add lib declaration for BroadcastChannel
  • Support inline annotations of function class fields
  • Fix $ObjMap documentation example.
  • add util.callbackify to node type def
  • Add documentation for $ObjMapi<T, F>
  • fix: return parameter for writable.setDefaultEncoding()
  • Model indexer keys as contravariant
  • WIP: Invert error and warning ordering
  • sketchy-boolean-op lint rule
  • Add `module.builtinModules`
  • fixed dom scrollIntoView to match latest specs
  • type_parser.ml's `properties` algorithm
  • Abstract class support
  • Fix type information for `Buffer.prototype.write`.
  • Add missing declarations for node copyFile and copyFileSync
  • Add support for ReactDOMServer renderToNodeStream and renderToStaticNodeStream
  • Add type definition for HTTP methods
  • Fixes #4564
  • Update $ObjMap example for Flow v0.57
  • Docs: Fix predicate functions anchor link
  • Docs: Remove `unsafe.enable_getters_and_setters`
  • Fix for setState definition
  • Add "destroy()" to stream$Stream
  • [Docs] correct $Keys<T> documentation logged value
  • Fix typo in documentation
  • [test]: Infinite merge with recursion
  • module.system.node.main_field
  • Type ReactDOM.render to correctly indicate that it may return null
  • Add definition for timingSafeEqual()
  • Add backgroundPositionX and backgroundPositionY style attributes.
  • Update hoc.md
  • Update config docs to warn about antipattern
  • Fix header formatting in intersections guide
  • Fix react-dom/test-utils annotations for functions that throw exceptions
  • Add WebAssembly libdefs
  • Fix examples in libdefs/creation page
  • correct type for readdir
  • Update assert.fail() definition
  • Update flow --help output example from 0.66 output
  • Update React libdefs for createContext, createRef
  • Add Fragment to the default export
  • Fix typo in Documentation
  • Website: Wrap long text
  • Add tuple types to WebGL uniform**v setters
  • Process .mjs files by default
  • Add buf.swap64() support
flow questions on Stackoverflow (View All Questions)
  • Is there a way to get JWT for WSO2 Identity Server password grant flow in a single call?
  • how to control the flow of the code inside a method which contains multiple for loop that linearly arrangged?
  • integrate flow checking into react-slingshot
  • Payment Flow using Square Credit Card Reader
  • Data Flow Graph Construction
  • Async data flow in React App with Redux + ReactRouter?
  • Linked list in data flow diagram
  • Simple flow management in Post-Redirect-Get pattern
  • Google authorization code flow - no refresh token
  • Integrating Custom Data Flow Component for Package SSIS in Visual Studio 2012
  • SSIS ERROR: The attempt to add a row to the Data Flow task buffer failed with error code 0xC0047020
  • What will the flow be like for connecting two BLE Peripherals?
  • How to get route id / flow id of a vehicle in veins?
  • What is the data flow when use OSS as registry backend?
  • Salesforce web flow in python
  • How do you include subroutine calls in a control flow graph?
  • Flow text around an image in (GitHub) Markdown
  • SwashBuckle/Swagger - OAuth Resource Owner Password Flow
  • Integration Service: How do I change the structure of a SQL Server table in a Data Flow task?
  • Data flow in computer networks
  • ASP.NET 5 JWT Bearer Token Flow
  • How do I see the number of rows processed in a data flow?
  • How to add a simple flow rule via OpenDaylight DLUX using the /operations/sal-flow:add-flow api
  • How can I capture the multimedia data flow from a remote website?
  • How to Implement Spring Web Flow in Spring Roo Application
  • can Meteor flow-routing accept any parameters for it dynamic routing?
  • how the Prestashop code will flow?
  • Is there a way to use Spring web flow to store flow data into persistent storage instead of sticking it to http session
  • Mixins with Flow type annotations
  • Flow type and merging json objects
flow latest release notes

Restore accidentally-deleted Object.setPrototypeOf library definition.

Likely to cause new Flow errors:

  • Replace some any-typed API definitions with actual types. This may cause errors in code that uses those APIs.

New Features:

  • find-refs now has support for object type properties.

Notable bug fixes:

  • find-refs can now find identifiers used as JSX component classes (e.g. <Foo/>).
  • Fix nontermination that could occur when printing types (e.g. for type-at-pos).

Misc:

  • Fix type-at-pos on method calls that have been affected by type refinements.
  • Add --profile flag to flow force-recheck.
  • Fix --retry-if-init false.
  • Improve type-at-pos location for opaque type declarations.
  • Add a message to the flow status output when the server is in lazy mode.
  • Include filename in flow ast output.
  • Add typings for ReactDOM.hydrate().
  • Make process.umask's argument optional.
  • Some miscellaneous improvements to code quality.

Parser:

  • Optional chaining parser support. This feature does not yet have type system support and should not be used.

New Features:

  • Error message redesign to help you better debug typing issues in your programs.
  • Upgrade global find-refs from experimental to beta.
  • Improve global find-refs performance by 2x-20x depending on the workload.
  • Support for CommonJS imports/exports with global find-refs.
  • Find usages of overridden instance methods with find-refs.
  • Improvements to type reporting services like type-at-pos and coverage thanks to a type normalizer rewrite. Notably, the normalizer and client services like type-at-pos now:
    • Make more aggressive use of type aliases, leading to more compact results,
    • Correctly distinguish between class types and their instance counterparts,
    • Report abstract type parameters themselves instead of their bounds, and
    • Precisely report recursive types.

Likely to cause new Flow errors:

  • Unresolved type variables internally unified with any no longer completely resolve to any. This may uncover new bugs in your programs where some inferred types silently resolved to any.
  • Fix type system stall for spreads of null and undefined. This meant programs like ({...null}: {p: number}); incorrectly passed Flow. If you were spreading a maybe-object type then Flow may catch some new bugs in your programs.
  • Because of the new error messages some suppression comments (configured with suppress_comment) will become unused since error locations moved.

Misc:

  • 3.5x performance improvement for some Facebook projects that makes heavy use of complicated unions of string literals such as GraphQL enums generated by Relay. (Performance improvements will scale with your usage of large string literal unions.)
  • Improve the nonstrict-import lint's error message.
  • Fix bug in React.cloneElement for stateless functional components.
  • Add --max-warnings flag which allows Flow to exit with a non-zero exit code if warnings are present.
  • Add --file-watcher flag to ignore file system events.
  • Expose url.format's urlObj argument type.
Other projects in OCaml