

Flow
====

 #### [Getting Started](getting-started)

  Never used a type system before or just new to Flow? Let's get you up and running in a few minutes. 

 #### [FAQ](faq)

  Have a question about using Flow? Check here first! 

 #### [Type Annotations](types)

  Learn how to add Flow type annotations to your code: Primitives, Objects, Functions, Classes, and more. 

 #### [Flow Enums](enums)

  Define a fixed set of constants which create their own type. Exhaustively checked in switch statements. 

 #### [Type System](lang)

  Learn how the type system in Flow works: Subtyping, Variance, Refinements, and more. 

 #### [CLI Commands](cli)

  How to use Flow from the command line. Including how to manage the Flow background process. 

 #### [Configuration](config)

  Flow tries to work out of the box as much as possible, but can be configured to work with any codebase. 

 #### [Library Definitions](libdefs)

  Learn how to create and use library definitions for the third-party code your code depends on. 

 #### [Declaration Files](declarations)

  Learn how to write types in .flow files. 

 #### [Error Suppressions](errors)

  Learn how to suppress Flow's type errors. 

 #### [React](react)

  Learn how to use Flow to effectively type common and advanced React patterns. 

 #### [Tools](tools)

  Detailed guides, tips, and resources on how to integrate Flow with different JavaScript tools. 

 #### [Editors](editors)

  Detailed guides, tips, and resources on how to integrate Flow with different code editors. 

 #### [Linting](linting)

  Learn how to configure Flow's linter to find potentially harmful code. 

 #### [Flow Strict](strict)

  Learn how to enable stricter type checking on a file-by-file basis. 



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/>

Type System
===========

 ### JavaScript: The Good and the Bad

 Developers like coding in JavaScript because it helps them move fast. The language facilitates fast prototyping of ideas via dynamic typing. The runtime provides the means for fast iteration on those ideas via dynamic compilation. This fuels a fast edit-refresh cycle, which promises an immersive coding experience that is quite appealing to creative developers.

 However, evolving and growing a JavaScript codebase is notoriously challenging. Developers cannot move fast when they break stuff. They hit frequent interruptions, spending a lot of time debugging silly mistakes, unraveling assumptions and guarantees made by libraries written by others, etc.

 In principle, this overhead can be mitigated by adding a layer of types to the codebase, and building tools that use type information to solve the above problems. For example, types can be used to identify bugs, to document interfaces of libraries, and so on.

 The idea of using types to manage code evolution and growth in JavaScript (and related languages) is not new. In fact, several useful type systems have been built for JavaScript in recent years. However, type systems differ in their goals. On one end of the spectrum are permissive type systems that provide some degree of linting against likely errors, without regard for correctness. On the other end of the spectrum are restrictive type systems that can guarantee the correctness of static code optimizations, at the cost of interoperability. Another area that has not seen a lot of focus is the performance of type checking itself.

 Flow: Goals
-----------

 Flow is a static type checker for JavaScript that we built at Facebook. The overall mission of Flow is to deliver an immersive coding experience for JavaScript developers—a fast edit-refresh cycle—even as the codebase evolves and grows. In engineering terms, we identify two concrete goals that are important to this mission: *precision* and *speed*. These goals pervasively drive the design and implementation.

 #### Precision

 JavaScript bugs can have significant impact at Facebook. Developers want to find and fix as many bugs as they can by the time their code rolls out into production. So we must care about soundness. At the same time, we must also care about not reporting too many spurious errors, because a low signal/noise ratio implies a low fix rate.

 In other words, we want Flow’s analysis to be precise in practice—it must model essential characteristics of the language accurately enough to understand the difference between idiomatic code and unintentional mistakes.

 Precision also has other desirable consequences. When types are trustworthy, developers tend to rely on them to structure their code and reason about it, leading to cleaner and more efficient code with fewer dynamic checks. When type errors are trustworthy, developers can focus on what their code does rather than thinking about how to rewrite their code to satisfy (or work around) the type system.

 Finally, precision enables useful developer tools to be built. In particular, the quality of results reported by Flow when the developer asks for the type of an expression, the definition reaching a reference, or the set of possible completions at a point through an IDE is correlated with the precision of Flow’s analysis.

 #### Speed

 Precision usually comes at the cost of speed. But while a precise analysis is desirable, most of the appeal of JavaScript is lost if we slow down the edit-refresh cycle by making developers wait as we compile.

 In other words, we must engineer Flow’s analysis to be extremely fast—it must respond to code changes without noticeable delay, while still being precise enough in practice.

 Like precision, speed also has other significant effects. When bugs are reported as the developer makes changes to code, they become part of the editing process—the developer doesn’t need to run the code to detect bugs, and tracing bugs back to the code becomes simpler. Similarly, when the IDE can show the type of an expression, the definition reaching a reference, etc. as the developer is coding, we have observed that productivity can improve dramatically.

 #### What makes Flow precise?

 One of the main contributors of Flow’s precision is path-sensitivity: the way types interact with runtime tests. The essence of many JavaScript idioms is to put together ad hoc sets of runtime values and to take them apart with shallow, structural (in)equality checks. In Flow, the set of runtime values that a variable may contain is described by its type, and a runtime test on that variable refines the type to a smaller set. This ability turns out to be quite powerful and general in practice.

 #### What makes Flow fast?

 The key to Flow’s speed is modularity: the ability to break the analysis into file-sized chunks that can be assembled later.

 Fortunately, JavaScript is already written using files as modules, so we modularize our analysis simply by asking that modules have explicitly typed signatures. (We still infer types for the vast majority of code “local” to modules.) Coincidentally, developers consider this good software engineering practice anyway.

 With modularity, we can aggressively parallelize our analysis. Furthermore, when files change, we can incrementally analyze only those files that depend on the changed files. Together, these choices have helped scale the analysis to millions of lines of code.

 Under the hood, Flow relies on a high-throughput low-latency systems infrastructure that enables distribution of tasks among parallel workers, and communication of results in parallel via shared memory. Combined with an architecture where the analysis of a codebase is updated automatically in the background on file system changes, Flow delivers near-instantaneous feedback as the developer edits and rebases code, even in a large repository.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/lang>

Getting Started
===============

 Flow is a static type checker for your JavaScript code. It does a lot of work to make you more productive. Making you code faster, smarter, more confidently, and to a bigger scale.

 Flow checks your code for errors through **static type annotations**. These *types* allow you to tell Flow how you want your code to work, and Flow will make sure it does work that way.

 
```
// @flow
function square(n: number): number {
  return n * n;
}

square("2"); // Error!

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/getting-started>

Flow Enums
==========

 Flow Enums define a fixed set of constants which create their own type.

 Unlike other features of Flow, Flow Enums exist as values at runtime, as well as existing as types.

 [Read how to enable Flow Enums in your project](enabling-enums).

 Benefits
--------

 Enums provide several benefits over existing patterns:

 * Reduce repetition: Enum declarations provide both the type and the value of the enum.
* Improve Flow performance: Enums are guaranteed to have good type-checking performance, unlike unions which may be expensive to type-check in certain situations.
* Enable new functionality: Enums come with a `cast` [method](using-enums#toc-methods), which converts from a primitive type to an enum type safely.
* Enhance safety: Enums define their own type which does not implicitly coerce to and from other types (e.g. from `string`s), and are required to be [exhaustively checked in switch statements](using-enums#toc-exhaustively-checking-enums-with-a-switch). These properties can help prevent logic bugs.

 Quickstart
----------

 ### 
[Defining enums](defining-enums)

 An enum named `Status` with three members: `Active`, `Paused`, and `Off`.

 
```
enum Status {
  Active,
  Paused,
  Off,
}

```
 By default, enums define members with string values which mirror their names. You can also explicitly set values:

 
```
enum Status {
  Active = 'active',
  Paused = 'paused',
  Off = 'off',
}

```
 You can use numbers as well:

 
```
enum Status {
  Active = 1,
  Paused = 2,
  Off = 3,
}

```
 Values must be unique, literals, and all of the same type. Check out the [full docs on defining enums](defining-enums) to learn more.

 ### 
[Using enums](using-enums)

 To access an enum member, use dot access:

 
```
Status.Active

```
 To use the enum type as an annotation, use the enum name:

 
```
const status: Status = Status.Active;

```
 Cast from the representation type (in this case, a `string`) to the enum type:

 
```
const status: Status | void = Status.cast(someString);

```
 You can easily provide a default value with the `??` operator:

 
```
const status: Status = Status.cast(someString) ?? Status.Off;

```
 Read more about the [other methods enums provide](using-enums#toc-methods), including `isValid`, `members`, and `getName`.

 Cast an enum type to its representation type (must be done explicitly):

 
```
(status: string)

```
 Checks of enums in `switch` statements are exhaustive - we ensure you check all members:

 
```
// ERROR: Incomplete exhaustive check: the member `Off` of enum `Status`
// has not been considered in check of `status`.
switch (status) {
  case Status.Active: ...; break;
  case Status.Paused: ...; break;
  // We forgot to add `case: Status.Off:` here, resulting in error above.
  // Using `default:` would also work to check all remaining members.
}

```
 Read more about [exhaustively checking enums](using-enums#toc-exhaustively-checking-enums-with-a-switch).

 Check out the [the full docs on using enums](using-enums) to learn more.

 When to use Flow Enums
----------------------

 If you previously defined a union type of literals, you can use an enum to define that type instead. Instead of

 
```
type Status =
  | 'Active'
  | 'Paused'
  | 'Off';

const x: Status = 'Active';

```
 or

 
```
const Status = Object.freeze({
  Active: 'Active',
  Paused: 'Paused',
  Off: 'Off',
});
type StatusType = $Keys<typeof Status>;
const x: StatusType = Status.Active;

```
 you can use:

 
```
enum Status {
  Active,
  Paused,
  Off,
}
const x: Status = Status.Active;

```
 See [migrating from legacy patterns](migrating-legacy-patterns) to learn more about migrating legacy JavaScript enum patterns to Flow Enums.

 When to not use Flow Enums
--------------------------

 Enums are designed to cover many use cases and exhibit certain benefits. The design makes a variety of trade-offs to make this happen, and in certain situations, these trade-offs might not be right for you. In those cases, you can continue to use existing patterns to satisfy your use cases. [Read more about those situations](using-enums#toc-when-to-not-use-enums).



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/enums>

Error Suppressions
==================

 Flow reports many different kinds of errors for many common programming mistakes, but not every JavaScript pattern can be understood by Flow. If you are confident your code is correct, and that Flow is erroring too conservatively, you can suppress the error so that Flow does not report it.

 What is a Suppression?
----------------------

 A suppression is a special kind of comment that you can place on the line before a type error. It tells Flow not to report that error when checking your code. Suppression comments look like the following:

 
```
// <SUPPRESSOR>[<CODE>] extra text
```
 A suppressor can be one of the following:

 * `$FlowFixMe`: for type errors that you intend to fix later
* `$FlowIssue`: for a type error that you suspect is an issue with Flow
* `$FlowExpectedError`: for a location where you expect Flow to produce a type error (for instance, when performing an invalid type cast).
* `$FlowIgnore`: for locations where you want Flow to ignore your code

 Note that all of the suppressors behave identically; we simply recommend using them as described here for your own ease of reference.

 The `<CODE>` portion of a suppression is optional, but when included specifies which [error code](#toc-making-suppressions-more-granular-with-error-codes) the suppression affects.

 Some examples of suppression comments:

 
```
// $FlowFixMe

// $FlowIssue[incompatible-type]

/* $FlowIgnore[prop-missing] some other text here */

/* $FlowFixMe[incompatible-cast] this
    is a multi-line
    comment */

{ /* $FlowIssue this is how you suppress errors inside JSX */ }
```
 In order to be a valid suppression comment, there are also some conditions that must be true:

 * No text can precede the suppressor, or come between the suppressor and the code. For example: `// some text then $FlowFixMe` is not a valid suppression, nor is `// $FlowIssue some text [incompatible-type]` or ` //$FlowFixMe [prop-missing]` (note the space here!).
* Suppressions must be on the line immediately before the error they suppress, otherwise they will not apply.

 Making Suppressions More Granular with Error Codes
--------------------------------------------------

 Suppressible Flow errors will also have an error code associated with them (after version 0.127). This code concisely describes the type of issue the error is reporting, and is different between different kinds of errors.

 In order to prevent suppressions from suppressing different kinds of type errors on the same line (by default suppressions without codes suppress every error on the following line), you can add an error code to your suppression. For example: `// $FlowFixMe[incompatible-type]` would only suppress errors with the `incompatible-type` code. So:

 
```
//$FlowFixMe[incompatible-type]
(3 : string);

```
 would report no errors, but

 
```
//$FlowFixMe[prop-missing]
(3 : string);

```
 would still report a type incompatibility.

 To suppress multiple error codes on the same line, you can stack suppression comments one after another, and they will all apply to the first non-comment line like so:

 
```
let y : number | { x : number }  = 1;

// $FlowFixMe[incompatible-type]
// $FlowFixMe[prop-missing]
(y.x : string);

```
 This will suppress both of the two errors on this line.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/errors>

Flow Strict
===========

 You can enable stronger safety guarantees in Flow (such as banning `any`/`Object`/`Function` types and requiring all dependencies to be typed) by adding **`@flow strict`** to your files.

 Overview
--------

 Flow was designed for easy adoption, so it allows you opt-out of type checking in certain situations, permitting unsafe behaviors. But since many codebases now have a high adoption of Flow types, this trade-off can be flipped. You can use *Flow Strict* to disallow previously-allowed unsafe patterns. This gives you improved safety guarantees that catch more bugs and make refactoring easier. And you can implement these stronger guarantees incrementally, on a file-by-file basis.

 Features
--------

 Enabling Flow Strict for a file means that several previously-allowed patterns will now trigger a Flow error. Each disallowed pattern has a corresponding [Flow Lint](https://flow.org/en/linting/) rule which triggers the error. The list of rules enabled for `@flow strict` is configured in each `.flowconfig`. Here are the recommended rules:

 * [`nonstrict-import`](https://flow.org/en/linting/rule-reference/#toc-nonstrict-import): Triggers an error when importing from a module which is not also `@flow strict`. This is very important, because it means that when a file is marked as strict, all of its dependencies are strict as well.
* [`unclear-type`](https://flow.org/en/linting/rule-reference/#toc-unclear-type): Triggers an error when using `Object`, `Function`, or `any` in a type annotation.
* [`untyped-import`](https://flow.org/en/linting/rule-reference/#toc-untyped-import): Triggers an error when importing from an untyped module.
* [`untyped-type-import`](https://flow.org/en/linting/rule-reference/#toc-untyped-type-import): Triggers an error when importing a type from an untyped module.
* [`unsafe-getters-setters`](https://flow.org/en/linting/rule-reference/#toc-unsafe-getters-setters): Triggers an error when using getters and setters, which can be unsafe.
* [`sketchy-null`](https://flow.org/en/linting/rule-reference/#toc-sketchy-null): Triggers an error when doing an existence check on a value that could be null/undefined or falsey.

 For a full list of available lint rules, see the [Lint Rule Reference](https://flow.org/en/linting/rule-reference/).

 Additionally, note that function parameters are considered const (i.e., treated as if they were declared with `const` rather than `let`). This feature is not yet configurable in Flow Strict; it is always on.

 Enabling Flow Strict in a .flowconfig
-------------------------------------

 Flow Strict is configured in each `.flowconfig`. To enable:

 1. Add a `[strict]` section to the `.flowconfig`.
2. List the lint rules to enable . These are strongly recommended: 
```
[strict]
nonstrict-import
unclear-type
unsafe-getters-setters
untyped-import
untyped-type-import
```
 Also recommended, but optional as it may be too noisy in some codebases: `sketchy-null`

 We recommend you enable all your desired rules from the beginning, then adopt Flow Strict file-by-file. This works better than enabling a single rule, adding `@flow strict` to many files, and then adding more rules to the config.

 Adoption
--------

 Add `@flow strict` to a file and fix all errors that appear. Because Flow Strict requires dependencies to also be strict (if the `nonstrict-import` rule is enabled), start at the leaves of the dependency tree and work up from there. Do not add `$FlowFixMe` to suppress the new errors as they appear; just add `@flow strict` once all issues have been resolved. Since the most common reasons for using `$FlowFixMe` stem from reliance on untyped dependencies or behavior, future issues should be greatly reduced once Flow Strict is enabled.

 Be liberal with enabling Flow Strict. Unlike adding or removing `@flow`, adding or removing `@flow strict` (by itself) does not change Flow coverage. It only prevents or allows certain new unsafe behavior from being added in the future. Even if in the future Flow Strict has to be disabled for the file, at least unsafe behavior was prevented from being added in the meantime.

 Library definitions are considered strict (as they can be included in many different projects with contradicting strict configurations).

 Strict Local
------------

 If you enable the `nonstrict-import` rule in your Flow Strict configuration (recommended), then all dependencies of a strict file must also be strict. While this the optimal goal, for large pre-existing codebases it may be beneficial to allow some of the benefits of Flow Strict to be put in use before all dependencies are strict.

 `@flow strict-local` is the same as `@flow strict`, except it does not require its dependencies to also be strict (i.e. it is “locally” strict). It does not have a separate configuration: it uses the same configuration as Flow Strict, just without the `nonstrict-import` rule.

 Once all the dependencies of a `@flow strict-local` file are strict, the file can be upgraded to a `@flow strict` file. A `@flow strict` file cannot depend on a `@flow strict-local` file as this would break the `nonstrict-import` rule.

 What’s Ahead
------------

 Eventually, some features of Flow Strict could become the default behavior of Flow, if those features prove successful and achieve widespread adoption.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/strict>

Flow CLI
========

 The flow command line tool is made to be easy-to-use for simple cases.

 Using the command `flow` will type-check your current directory if the `.flowconfig` file is present. A flow server will automatically be started if needed.

 The CLI tool also provides several other options and commands that allow you to control the server and build tools that integrate with Flow. For example, this is how the [Nuclide](https://nuclide.io/) editor integrates with Flow to provide autocompletion, type errors, etc. in its UI.

 To find out more about the CLI just type:

 
```
flow --help
```
 This will give you information about everything that flow can do. Running this command should print something like this:

 
```
Usage: flow [COMMAND] [PROJECT_ROOT]

Valid values for COMMAND:
  ast              Print the AST
  autocomplete     Queries autocompletion information
  batch-coverage   Shows aggregate coverage information for a group of files or directories
  check            Does a full Flow check and prints the results
  check-contents   Run typechecker on contents from stdin
  config           Read or write the .flowconfig file
  coverage         Shows coverage information for a given file
  cycle            Output .dot file for cycle containing the given file
  find-module      Resolves a module reference to a file
  find-refs        Gets the reference locations of a variable or property
  force-recheck    Forces the server to recheck a given list of files
  get-def          Gets the definition location of a variable or property
  get-imports      Get names of all modules imported by one or more given modules
  graph            Outputs dependency graphs of flow repositories
  init             Initializes a directory to be used as a flow root directory
  ls               Lists files visible to Flow
  lsp              Acts as a server for the Language Server Protocol over stdin/stdout [experimental]
  print-signature  Prints the type signature of a file as extracted in types-first mode
  server           Runs a Flow server in the foreground
  start            Starts a Flow server
  status           (default) Shows current Flow errors by asking the Flow server
  stop             Stops a Flow server
  type-at-pos      Shows the type at a given file and position
  version          Print version information

Default values if unspecified:
  COMMAND         status
  PROJECT_ROOT    current folder

Status command options:
  --color              Display terminal output in color. never, always, auto (default: auto)
  --from               Specify client (for use by editor plugins)
  --help               This list of options
  --json               Output results in JSON format
  --no-auto-start      If the server is not running, do not start it; just exit
  --old-output-format  Use old output format (absolute file names, line and column numbers)
  --one-line           Escapes newlines so that each error prints on one line
  --quiet              Suppresses the server-status information that would have been printed to stderr
  --retries            Set the number of retries. (default: 3)
  --show-all-errors    Print all errors (the default is to truncate after 50 errors)
  --strip-root         Print paths without the root
  --temp-dir           Directory in which to store temp files (default: /tmp/flow/)
  --timeout            Maximum time to wait, in seconds
  --version            Print version number and exit
```
 Example with custom project root:

 
```
mydir
├── frontend
│   ├── .flowconfig
│   └── app.js
└── backend
```
 
```
flow check frontend
```
 You can then, further dig into particular COMMANDs by adding the `--help` flag.

 So, for example, if you want to know more about how the autocomplete works, you can use this command:

 
```
flow autocomplete --help
```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/cli>

Library Definitions
===================

 What’s a “Library Definition”?
------------------------------

 Most real JavaScript programs depend on third-party code and not just code immediately under the control of the project. That means a project using Flow may need to reference outside code that either doesn’t have type information or doesn’t have accurate and/or precise type information. In order to handle this, Flow supports the concept of a “library definition” (AKA “libdef”).

 A libdef is a special file that informs Flow about the type signature of some specific third-party module or package of modules that your application uses. If you’re familiar with languages that have header files (like `C++`), you can think of libdefs as a similar concept.

 These special files use the same `.js` extension as normal JS code, but they are placed in a directory called `flow-typed` in the root directory of your project. Placement in this directory tells Flow to interpret them as libdefs rather than normal JS files.

 
>  NOTE: Using the `/flow-typed` directory for libdefs is a convention that enables Flow to JustWork™ out of the box and encourages consistency across projects that use Flow, but it is also possible to explicitly configure Flow to look elsewhere for libdefs using the [`[libs]` section of your `.flowconfig`](https://flow.org/en/config/libs).
> 
>  

 General Best Practices
----------------------

 **Try to provide a libdef for each third-party library your project uses**

 If a third-party library that has no type information is used by your project, Flow will treat it like any other untyped dependency and mark all of its exports as `any`. Interestingly, this is the only place that Flow will implicitly inject `any` into your program.

 Because of this behavior, it is a best practice to find or write libdefs for as many of the third-party libraries that you use as you can. We recommend checking out the `flow-typed` [tool and repository](https://github.com/flowtype/flow-typed/blob/master/README.md) , which helps you quickly find and install pre-existing libdefs for your third-party dependencies.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/libdefs>

Getting Started
===============

 Developers will often use Flow and React together, so it is important that Flow can effectively type both common and advanced React patterns. This guide will teach you how to use Flow to create safer React applications.

 In this guide we will assume you know [the React basics](https://facebook.github.io/react/docs/hello-world.html) and focus on adding types for patterns you are already familiar with. We will be using examples based on `react-dom`, but all of these patterns work in other environments like `react-native` as well.

 Setup Flow with React
---------------------

 Flow and Babel work well together, so it doesn’t take much to adopt Flow as a React user who already uses Babel. If you need to setup Babel with Flow, you can follow [this guide](https://flow.org/en/tools/babel/).

 Babel also [works out of the box with Create React App](https://flow.org/en/tools/create-react-app/), just install Flow and create a `.flowconfig`.

 React Runtimes
--------------

 Flow supports the `@babel/plugin-transform-react-jsx` runtime options required to use JSX without explicitly importing the React namespace.

 If you are using the new automatic runtime, use this configuration in your `.flowconfig` so that Flow knows to auto-import `jsx`:

 
```
[options]
react.runtime=automatic
```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/react>

Tools
=====

   [###  Babel

  Learn how to use Flow with Babel](tools/babel)   [###  ESLint

  Learn how to use Flow with ESLint](tools/eslint)   [###  flow-remove-types

  Learn how to use Flow with flow-remove-types](tools/flow-remove-types)   [###  Create React App

  Learn how to use Flow with Create React App](tools/create-react-app)  

 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/tools>

Linting Overview
================

 Flow contains a linting framework that can tell you about more than just type errors. This framework is highly configurable in order to show you the information you want and hide the information you don’t.

 Configuring Lints in the `.flowconfig`
--------------------------------------

 Lint settings can be specified in the `.flowconfig` [lints] section as a list of `rule=severity` pairs. These settings apply globally to the entire project.

 **Example:**

 
```
[lints]
# all=off by default
all=warn
untyped-type-import=error
sketchy-null-bool=off
```
 Configuring Lints from the CLI
------------------------------

 Lint settings can be specified using the `--lints` flag of a Flow server command as a comma-delimited list of `rule=severity` pairs. These settings apply globally to the entire project.

 **Example:**

 
```
flow start --lints "all=warn, untyped-type-import=error, sketchy-null-bool=off"
```
 Configuring Lints with Comments
-------------------------------

 Lint settings can be specified inside a file using `flowlint` comments. These settings apply to a region of a file, or a single line, or part of a line. For more details see [Flowlint Comments](flowlint-comments).

 **Example:**

 
```
 /* flowlint
  *   sketchy-null:error,
  *   untyped-type-import:error
  */
const x: ?number = 0;

if (x) {} // Error
import type {Foo} from './untyped.js'; // Error

// flowlint-next-line sketchy-null:off
if (x) {} // No Error

if (x) {} /* flowlint-line sketchy-null:off */ // No Error

// flowlint sketchy-null:off
if (x) {} // No Error
if (x) {} // No Error
import type {Bar} from './untyped.js'; // Error; unlike a $FlowFixMe, a flowlint comment only suppresses one particular type of error.
// flowlint sketchy-null:error

```
 Lint Settings Precedence
------------------------

 Lint settings in `flowlint` comments have the highest priority, followed by lint rules in the `--lints` flag, followed by the `.flowconfig`. This order allows you to use `flowlint` comments for fine-grained linting control, the `--lints` flag for trying out new lint settings, and the `.flowconfig` for stable project-wide settings.

 Within the -lints flag and the flowconfig, rules lower down override rules higher up, allowing you to write things like

 
```
[lints]
sketchy-null=warn
sketchy-null-bool=off
```
 The lint settings parser is fairly intelligent and will stop you if you write a redundant rule, a rule that gets completely overwritten, or an unused suppression. This should prevent most accidental misconfigurations of lint rules.

 Severity Levels and Meanings
----------------------------

 **off:** The lint is ignored. Setting a lint to `off` is similar to suppressing a type error with a suppression comment, except with much more granularity.

 **warn:** Warnings are a new severity level introduced by the linting framework. They are treated differently than errors in a couple of ways:

 * Warnings don’t affect the exit code of Flow. If Flow finds warnings but no errors, it still returns 0.
* Warnings aren’t shown on the CLI by default, to avoid spew. CLI warnings can be enabled by passing the –include-warnings flag to the Flow server or the Flow client, or by setting “include\_warnings=true” in the `.flowconfig`. This is good for smaller projects that want to see all project warnings at once.
* Warnings have special [IDE Integration](ide-integration).

 **error:** Lints with severity `error` are treated exactly the same as any other Flow error.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/linting>

Type Annotations
================

 Adding type annotations is an important part of your interaction with Flow.

 Flow has a powerful ability to infer the types of your programs. The majority of your code can rely on it. Still, there are places where you’ll want to add types.

 Imagine the following `concat` function for concatenating two strings together.

 
```
function concat(a, b) {
  return a + b;
}

```
 When you use this function, Flow knows exactly what is going on.

 
```
concat("A", "B"); // Works!

```
 However, you can use the `+` operator on strings or numbers, so this would also be valid.

 
```
concat(1, 2); // Works!

```
 But suppose you only want to allow strings in your function. For that you can add types.

 
```
function concat(a: string, b: string) {
  return a + b;
}

```
 Now you’ll get a warning from Flow if you try to use numbers.

 
```
// @flow
function concat(a: string, b: string) {
  return a + b;
}

concat("A", "B"); // Works!
concat(1, 2); // Error!

```
 Setting up “boundaries” with your types means you can tell Flow your intent on top of the inference it already does.

 This guide will teach you the syntax and semantics of all the different types you can have in Flow.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types>

Declaration Files
=================

 What’s a Declaration File?
--------------------------

 Let’s look at a more general, and sometimes more convenient way to declare types for modules: `.flow` files.

 There are two possible use cases, depending on whether an implementation file exists or not.

 In the first case, the exported types of a module are declared in a *declaration file* `<FILENAME>.flow`, that is located in the same directory as the corresponding *implementation file* `<FILENAME>`. The declaration file completely shadows the colocated implementation. In other words, Flow will completely ignore `<FILENAME>` and just read `<FILENAME>.flow` instead.

 In the second case, the implementation file is missing entirely. `<FILENAME>.flow` is treated as if it is named `<FILENAME>`.

 Note that the `.flow` extension applies both to `.js` files as well as `.json` ones. The corresponding declaration files have extensions `.js.flow` and `.json.flow`, respectively.

 Now let’s see an example of the first case documented above. Suppose we have the following code in a file `src/LookBeforeYouLeap.js`:

 
```
// @flow
import { isLeapYear } from "./Misc";
if (isLeapYear("2020")) console.log("Yay!");

```
 and suppose that `src/Misc.js` has an incompatible implementation of `isLeapYear`:

 
```
// @flow
export function isLeapYear(year: number): boolean {
  return year % 4 == 0; // yeah, this is approximate
}

```
 If we now create a declaration file `src/Misc.js.flow`, the declarations in it will be used instead of the code in `src/Misc.js`. Let’s say we have the following declarations in `src/Misc.js.flow`.

 
>  NOTE: The syntax for declarations in a declaration file is the same as we’ve seen in [Creating Library Definitions section](https://flow.org/en/libdefs/creation).
> 
>  

 
```
// @flow
declare export function isLeapYear(year: string): boolean;

```
 What do you think will happen?

 Right, the `isLeapYear` call in `src/LookBeforeYouLeap.js` will typecheck, since the `year` parameter expects a `string` in the declaration file.

 As this example shows, declaration files must be written with care: it is up to the programmer to ensure they are correct, otherwise they may hide type errors.

 Inlining declarations in regular code
-------------------------------------

 Sometimes it is useful to make declarations inline, as part of the source of an implementation file.

 In the following example, say you want to finish writing the function `fooList` without bothering to mock up its dependencies first: a function `foo` that takes a `number` and returns a `string`, and a class `List` that has a `map` method. You can do this by including declarations for `List` and `foo`:

 
```
declare class List<T> {
  map<U>(f: (x: T) => U): List<U>;
}
declare function foo(n: number): string;

function fooList(ns: List<number>): List<string> {
  return ns.map(foo);
}

```
 Just don’t forget to replace the declarations with proper implementations.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/declarations>

Editors
=======

 You can benefit from having Flow run as you develop by integrating into your editor.

 Editor plugins are provided and maintained by the community. If you have trouble configuring or using a specific plugin for your IDE, please visit the project’s repo or search for a community provided answer.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/editors>

FAQ
===

 I checked that `foo.bar` is not `null`, but Flow still thinks it is. Why does this happen and how can I fix it?
---------------------------------------------------------------------------------------------------------------

 Flow does not keep track of side effects, so any function call may potentially nullify your check. This is called [refinement invalidation](lang/refinements#toc-refinement-invalidations).

 Example ([https://flow.org/try](https://flow.org/try/#0C4TwDgpgBACghgJzgWygXigbwFBSgI0QC4oB+AZ2AQEsA7AcwBpsBfbAMwFdaBjYagPa0oyEADFuPABTsBAkvCTIAlCUo0GWXFGrsoMuQDpCCZVrx4eQ8gIA2EQ7YH0pAIh4ALCDwDWEACYAhK7KANzaAJAIEMCcCMKyAsaIoVAA9GlQ7E4A7lAQCAgCCOSGUACSeiACnFBWyMgQtMBQwF511nYOTkw6LTnFPuTabHja0bHxUK7+EOxwnLYt6nT0ruEsQA)):

 
```
// @flow
type Param = {
  bar: ?string,
}
function myFunc(foo: Param): string {
  if (foo.bar) {
    console.log("checked!");
    return foo.bar; // Flow errors. If you remove the console.log, it works
  }

  return "default string";
}

```
 You can get around this by storing your checked values in local variables:

 
```
// @flow
type Param = {
  bar: ?string,
}
function myFunc(foo: Param): string {
  if (foo.bar) {
    const bar = foo.bar;
    console.log("checked!");
    return bar; // Ok!
  }

  return "default string";
}

```
 I checked that my object is of type A, so why does Flow still believe it’s A | B?
---------------------------------------------------------------------------------

 Refinement invalidation can also happen with [disjoint unions](types/unions#toc-disjoint-unions). Any function call will invalidate any refinement.

 Example ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQAXAngBwKagEqYM7qwB2+2AvKIqKAD6gDeoaWAXKAOT4CuAxrwXwcANKABuAQ2jdM7fMgBOAS2IBzUAF9qdRswyzOmBQtgKRoIyYXsAosdOaA3IkS8S80AAsJxACbRMPEJ3ClAACgUCIlIDIOiyAEpQcgA+Rm0lSHDI4JiAOhYKckouPgF8ISSGbRoyZAAVJQBbTFhuZDCwpNT0mj7QN1JYALy4VTCAAwASBhz4zDzJaUwNUABGCYSazVE1gAYDhOcaLQ1HIA)):

 
```
// @flow
type Response =
  | { type: 'success', value: string }
  | { type: 'error', error: Error };

const handleResponse = (response: Response) => {
  if (response.type === 'success') {
    setTimeout(() => {
      console.log(`${response.value} 1`)
    }, 1000);
  }
};

```
 Here, a work around would be to extract the part of the value you’re interested in, or to move the if check inside the `setTimeout` call:

 Example ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQAXAngBwKagEqYM7qwB2+2AvKIqKAD6gDeoaWAXKAOT4CuAxrwXwcANKABuAQ2jdM7fMgBOAS2IBzUAF9qdRswyzOmBQtgKRoIyYXsAosdOaA3IkS8S80AAsJxACbRMPEJ3ClAACgUCIlIDIOiyAEpQcgA+Rm0lSHDI4JiAOhYKckouPgF8ISSGbRo3UmRxKRlk0Bz4zDzJaUwa0DJkABUlAFtMWG5kMLCk1PSaedA6-FgAvLhVMIADABIGLpkNUABGTYTejVEjgAYbhOcaLQ1HIA)):

 
```
// @flow
type Response =
  | { type: 'success', value: string }
  | { type: 'error', error: Error };

const handleResponse = (response: Response) => {
  if (response.type === 'success') {
    const value = response.value
    setTimeout(() => {
      console.log(`${value} 1`)
    }, 1000);
  }
};

```
 I’m in a closure and Flow ignores the if check that asserts that `foo.bar` is defined. Why?
-------------------------------------------------------------------------------------------

 In the previous section we showed how refinement is lost after a function call. The exact same thing happens within closures, since Flow does not track how your value might change before the closure is called.

 Example ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQAXAngBwKagAqYE4DOsAdqALygDeAhgOaYBcoA-CQK4C2ARgQL6IAxqULJQWWOmjZKAbVoNmARgBMfADTV6TUEoAcGrYtAqALHwC6AbiEixsaABM8RUsxfEylBToDsABj4bAEtIUAAKB2cCTwA6bQBKakRQcUxJaVjIWHwAURpBAAtwrFcvAD5k1NThEmJMuDpwgAMAFULsUs9QYMJQABIqLtJ4hj5QGhJHUGQO0Cj5kmxegaoojxHtPmaEm1S+BMQ+IA)):

 
```
// @flow
type Person = {age: ?number}
const people = [{age: 12}, {age: 18}, {age: 24}];
const oldPerson: Person = {age: 70};
if (oldPerson.age) {
  people.forEach(person => {
    console.log(`The person is ${person.age} and the old one is ${oldPerson.age}`);
  })
}

```
 The solution here is to move the if check in the `forEach`, or to assign the `age` to an intermediate variable.

 Example ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQAXAngBwKagAqYE4DOsAdqALygDeAhgOaYBcoA-CQK4C2ARgQL6IAxqULJQWWOmjZKAbVoNmARgBMfADTV6TUEoAcGrYtAqALHwC6AbiEixsaABM8RUsxfEylBToDsABj4bAEtIUAAKB2cCTwA6bQBKakRQUGESUVBtClAoj1J4hhtUiSlMWMhYfABRGkEAC3CsVy8APmTU1PTiaVi4OnCAAwAVeuxmz1BgwlAAEioJgu0+LJJHUGQx3KdckmxpuZ8+QYTi0D4ExD4gA)):

 
```
// @flow
type Person = {age: ?number}
const people = [{age: 12}, {age: 18}, {age: 24}];
const oldPerson: Person = {age: 70};
if (oldPerson.age) {
  const age = oldPerson.age;
  people.forEach(person => {
    console.log(`The person is ${person.age} and the old one is ${age}`);
  })
}

```
 But Flow should understand that this function cannot invalidate this refinement, right?
---------------------------------------------------------------------------------------

 Flow is not [complete](https://flow.org/en/lang/types-and-expressions/#soundness-and-completeness), so it cannot check all code perfectly. Instead, Flow will make conservative assumptions to try to be sound.

 Why can’t I use a function in my if-clause to check the type of a property?
---------------------------------------------------------------------------

 Flow doesn’t track refinements made in separated function calls.

 Example ([https://flow.org/try](https://flow.org/try/#0MYewdgzgLgBAhgEwTAvDAFAMwJYCdoBcMYArgLYBGAprgDQwRWhgJGmU0CUqAfDDvlgBqBk3AIA3AChm0GADc4AGyLRc2MAHMYAH2LlquVDACM02bGwQAcgZrH0ipSSoAVEACUqOMFTZ2jPTUNTW4UPigATwAHKhBMBWUXdy8fKlQUNABydkMs6WwE9CtbDlxHZU5uRAQKpXoAJk4JIA))

 
```
// @flow
const add = (first: number, second: number) => first + second;
const val: string | number = ...
const isNumber = (valueToRefine: ?number) => typeof valueToRefine === 'number';
if (isNumber(val)) add(val, 2);

```
 However, Flow has [predicates functions](types/functions#toc-predicate-functions) that can do these checks via `%checks`.

 Example ([https://flow.org/try](https://flow.org/try/#0MYewdgzgLgBAhgEwTAvDAFAMwJYCdoBcMYArgLYBGAprgDQwRWhgJGmU0CUqAfDDvlgBqBk3AIA3AChm0GADc4AGyLRc2MAHMYAH2LlquVDACM02bGwQAcgZrH0ipSSoAVEACUqOMFTZ2jPTUNTU4iAFJgAAsmAGsIXhgoAE8AByoQTAVlF3cvHypUFDQAcnZDEulsLPQrWw5cR2VObkQEJqV6ACZOCSA))

 
```
// @flow
const add = (first: number, second: number) => first + second;
const val: string | number = ...
const isNumber = (valueToRefine: ?number): %checks => typeof valueToRefine === 'number';
if (isNumber(val)) add(val, 2);

```
 Why can’t I pass an `Array<string>` to a function that takes an `Array<string | number>`
----------------------------------------------------------------------------------------

 The function’s argument allows `string` values in its array, but in this case Flow prevents the original array from receiving a `number`. Inside the function, you would be able to push a `number` to the argument array, causing the type of the original array to no longer be accurate. You can fix this error by changing the type of the argument to `$ReadOnlyArray<string | number>`. This prevents the function body from pushing anything to the array, allowing it to accept narrower types.

 As an example, this would not work:

 
```
// @flow

const fn = (arr: Array<string | number>) => {
  // arr.push(123) NOTE! Array<string> passed in and after this it would also include numbers if allowed
  return arr;
};

const arr: Array<string> = ['abc'];

fn(arr); // Error!

```
 but with `$ReadOnlyArray` you can achieve what you were looking for:

 
```
// @flow
const fn = (arr: $ReadOnlyArray<string | number>) => {
  // arr.push(321) NOTE! Since you are using $ReadOnlyArray<...> you cannot push anything to it
  return arr;
};

const arr: Array<string> = ['abc'];

fn(arr);

```
 Example ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQiSgOoEsAuALWBXLUAJwFMBDAE1gDtoBPALmQGNaBnIyGgRlAF5QACnLFijUAEEx5egB5OxDDQDmoAD4ACmvgC2AI1LEAfAEoBx0AG9EASFSjiAOgAO+djiE8ATAGZzqAByAPIAKgCiAIRSMvKKyiqWLuTs7KSUoMqg5DQZ5JBYRqC4GOyZRPAE0HnQ7LCZNCzQ+JSkoDoGRmUYkNnQcPDpdmRY+MQ02WIA3IgAvqwcRI48EtLEsgpYSqqWggDaAOTk+iwHALozKGDcPCJiplOgqHIAtG+g+I2wurqkNFywYigIzEQHsSKRZCoN4w2Fw+EIxFIqFgABKFGodHoLwAbl0MLRmIg2DROKBuN4BMJHBIACToqjBLFrDbxVQabR6Qwmcz8Sw2UCCp5gRyudyeXzeHgBMAhCLRADKyhYbXoBEmbXcCVA9IxTIYLPkTmNljV+FALByNFgRDcHmyNHoJXZWHq2GGpFG40mxDmC1JSzE3lWsU220SVMOx1OF2QFLuxG8DyAA))

 Why can’t I pass `{ a: string }` to a function that takes `{ a: string | number }`
----------------------------------------------------------------------------------

 The function argument allows `string` values in its field, but in this case Flow prevents the original object from having a `number` written to it. Within the body of the function you would be able to mutate the object so that the property `a` would receive a `number`, causing the type of the original object to no longer be accurate. You can fix this error by making the property covariant (read-only): `{ +a: string | number }`. This prevents the function body from writing to the property, making it safe to pass more restricted types to the function.

 As an example, this would not work:

 
```
// @flow

const fn = (obj: {| a: string | number |}) => {
  // obj.a = 123;
  return obj;
};

const object: {| a: string |} = {a: 'str' };

fn(object); // Error!

```
 but with a covariant property you can achieve what you were looking for:

 
```
// @flow
const fn = (obj: {| +a: string | number |}) => {
  // obj.a = 123 NOTE! Since you are using covariant {| +a: string | number |}, you can't mutate it
  return obj;
};

const object: {| a: string |} = { a: 'str' };

fn(object);

```
 Example ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQiSgOoEsAuALWBXLUAJwFMBDAE1gDtoBPALmQGNaBnIyGgRlAF5QAClgAjAFaNQAbwA+oclM7EMNAOahZAApr4AtqNLEtsgL4BKAQD4ZiAJCox4gHTkBoHgCYAzKBAA5AHkAFQBRAEIZbUVQZVUNM1AAB3J2dlJKUFUFGkzySCwjUFwMdiyieAJoTMNQXQMijEgFaDh4DPsyLHxiGlAnAG5EU1YOIidSFiweKTktGLj1TVN3aRiAcmV10FMhlDBuHhEJSenzAb8wAB4AWjvQfBo2PT1SGiJsyFhiUCNib-Y4XCyFQdzB4IhkKh0JhILAACUKNQ6PQbgA3IzsDC0ZiINg0TigbiedzHSRRUAAagWWBUS209UMPzMln4NmkiFAoAcYCcrncXl8ARCEVAAGVVCxSKB6AQFGQHlilmw0eQVOR3lEtNSlLT4podPomcsADQyuUsDXrIh6QjkQrlTqkbq9foSIYjPFjN3iU6eWbyGl0hIrQTSBRSTa07a7ZDEsl+85AA))

 Why can’t I refine a union of objects?
--------------------------------------

 There are two potential reasons:

 1. You are using inexact objects.
2. You are destructuring the object. When destructuring, Flow loses track of object properties.

 Broken example:

 
```
/* @flow */

type Action =
  | {type: 'A', payload: string}
  | {type: 'B', payload: number};

// Not OK
const fn = ({type, payload}: Action) => {
  switch (type) {
    case 'A': return payload.length;
    case 'B': return payload + 10;
  }
}

```
 Fixed example:

 
```
/* @flow */

type Action =
  | {type: 'A', payload: string}
  | {type: 'B', payload: number};

// OK
const fn = (action: Action) => {
  switch (action.type) {
    case 'A': return action.payload.length;
    case 'B': return action.payload + 10;
  }
}

```
 ([https://flow.org/try](https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVAXAngBwKZgCCAxhgJZwB2YAvGKmGAD5gDe2+AXGAOSE8AaMDgCGWeCIAm3AM4YATmUoBzAL6MGzNhzzceAIUHCxE6WEoBXALYAjPPNUBudMGBgA8gGlUxKnLBQAIy0YAAUIqQUlNwk5FQAlLQAfGyaMghkGMQAFmERcZQAdDqJrJqMxCIyBHw83PJ4GBby1PlRhaLicFKFMHgqGNnOjBVVNYb1jc2tkVQdJt2SYADUYIEADMNgqqg7Lm4AcnAYHp5gFpS+Vlb9J1Bw8mD28g8yAISorr6U-lAATCFQuxcHghJ1TKoYrNKIkaCkyq5GOlMjkwiVUoiRpVqrx+JMmi1jF0en0BkNPm4sWNeBMwA0CdRwYsVmtNhTGDtEaogA))

 Second example:

 * broken: [https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQBLAtgB1gJwC6gFSgCGAzqAEoCmRAxnpFrKqAORbV0uKI4Ce6lUAGUArgCMAjAAVG6MgF5QAb2IAuUADsRqMZSwAaUGPVade0AF8A3D36DRYgEwzYc0IpVF1JHFmQaAc0Mab19-AMsbRBpYDR9hcQl3UAAKdFkSdQdpDIBKdwA+UAAeABNkADdQYAKbGLi8B0dktIys8Wc8wpLyqpqo+viAYSYWpURQUBJKaEo6bH0J0AA6VfTXEkQLdRVp2fmsdV8RSkNV5eyXNwtQAB9lKZm5nGx1SCJoabPVpquyC3y8gKSz2z2woAA-CVsspzus5DcaqB1MUmrC1hlEbUgA)
* fixed: [https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQBLAtgB1gJwC6gFSgCGAzqAEoCmRAxnpFrKqAORbV0uKI4Ce6lUAGUArgCMAjAAVG6MgF5QAbwA+xAFygAdiNRjKWADSgxmnXoOgVAXwDcPfoNFiATDNhzQi1RtAkcWMhaAObGNJr+gSFWdtw0sFr+wuISXqAAFOiyJJrO0tkAlF4AfKAAPAAmyABuoMDF9vGJeM4uaZnZueJuhSXlVbX19ohNSQDCTO1ZHjnKaiSU0JR02JoBIpTGAHQ7ee6eNlZzfovLOKugkETQC9u73ftkNkXypUqIoKDIkBnTclsLJYrLBFd6fT5LPBKQFnbB3LbsfzWNJ-Ej2cGgdg4ERYLTlPLKHYIyhIuoND6gZGLBbKCkQyhQmHA+GInDIxSo9HgrE4vFlVqEnas5FDCnWRDWIA)

 I got a “Missing type annotation” error. Where does it come from?
-----------------------------------------------------------------

 Flow requires type annotations at module boundaries to make sure it can scale. To read more about that, check out our [blog post](https://medium.com/flow-type/asking-for-required-annotations-64d4f9c1edf8) about that.

 The most common case you’ll encounter is when exporting a function or React component. Flow requires you to annotate inputs. For instance, in this [example](https://flow.org/try/#0PTAEAEDMBsHsHcBQBTAHgB1gJwC6gMawB2AzngIYAmloAvKOXQHwOgDUoAjANxA), flow will complain:

 
```
export const add = a => a + 1;

```
 The fix here is to add types to the parameters of `add`.

 Example ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQBTAHgB1gJwC6gMawB2AzngIYAmloAvKABTkBcoRArgLYBGyWAlHQB8ocqADUoAIwBuIA)):

 
```
export const add = (a: number) => a + 1;

```
 To see how you can annotate exported React components, check out our docs on [HOCs](https://flow.org/en/react/hoc/#toc-exporting-wrapped-components).

 There are other cases where this happens, and they might be harder to understand. You’ll get an error like `Missing type annotation for U` For instance, you wrote this [code](https://flow.org/try/#0PTAEAEDMBsHsHcBQiDGsB2BnALqAhgE4F4CeoAvKANoDkeNANKDQEY0C6iApgB4AOsArjRZcAcy7ouBAJYoAgkVIV8SkgDoAtnj4AKPBQB8+AJRA):

 
```
const array = ['a', 'b']
export const genericArray = array.map(a => a)

```
 Here, Flow will complain on the `export`, asking for a type annotation. Flow wants you to annotate exports returned by a generic function. The type of `Array.prototype.map` is `map<U>(callbackfn: (value: T, index: number, array: Array<T>) => U, thisArg?: any): Array<U>`. The `<U>` corresponds to what is called a [generic](types/generics), to express the fact that the type of the function passed to map is linked to the type of the array.

 Understanding the logic behind generics might be useful, but what you really need to know to make your typings valid is that you need to help Flow to understand the type of `genericArray`.

 You can do that by adding an explicit type argument:

 
```
const array = ['a', 'b'];
export const genericArray = array.map<string>(a => a);

```
 or by annotating the exported constant ([https://flow.org/try](https://flow.org/try/#0PTAEAEDMBsHsHcBQBjWA7AzgF1AQwE764CeoAvKANoDku1ANKNQEbUC6iApgB4AOs+HKkw4A5pzSd8AS2QBBQiQBcoBUWIAebDLSiAfOTyLiAOgC2uXgApc5A7gCUQA)):

 
```
const array = ['a', 'b']
export const genericArray: Array<string> = array.map(a => a)

```
 Flow cannot understand the types of my higher order React component, how can I help it?
---------------------------------------------------------------------------------------

 Typings HOCs can be complicated. While you can follow the [docs about it](react/hoc), sometimes it can be easier to type the returned component.

 For instance, in this [example](https://flow.org/try/#0PTAEAEDMBsHsHcBQBLAtgB1gJwC6gFSgCGAzqAEoCmRAxnpFrKqAORbV0sDciiNsAOxJ4SlHABUAnukqgAvKABCpSgGEmmAZQF45APlDpG6MvtAAeZaPUZB2vAG8AdC6OwTAX1A5plOQCIAIwBXHBxBf1BgPR5+ITwAcW1KLGQaRVDwgXlQAAoHHxkAGlAaAAtkaAATdgEPAEp5A3MQsMFvXzkC3y9BVWg0gGsu3MazOJJYaEonOABzXJYaAZpByiqWeo89B3LKmu0Pc2BWrJjeCbwMtoEALgoOHCcbTXspGXNdiura+6paJ4AOVgVUo2xyogkvlySS0qXSmUE9S4QA), we don’t type the HOC (setType), but the component created with it, `Button`. To do so, we use the type `React.ComponentType`.

 
```
// @flow
import * as React from 'react';

const setType = BaseComponent => props => <BaseComponent {...props} type="button" />;
const GenericButton = ({type, children}) => <button type={type} onClick={() => console.log('clicked')}>{children}</button>;

const Button: React.ComponentType<{children: React.Node}> = setType(GenericButton);

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/faq>

.flowconfig
===========

 Every Flow project contains a `.flowconfig` file. You can configure Flow by modifying `.flowconfig`. New projects or projects that are starting to use Flow can generate a default `.flowconfig` by running `flow init`.

 
`.flowconfig` format
---------------------

 The `.flowconfig` uses a custom format that vaguely resembles INI files.

 The `.flowconfig` consists of different sections:

 * [`[include]`](include)
* [`[ignore]`](ignore)
* [`[untyped]`](untyped)
* [`[libs]`](https://flow.org/en/docs/libs)
* [`[lints]`](lints)
* [`[options]`](options)
* [`[version]`](version)
* [`[declarations]`](declarations)
* [`[strict]`](https://flow.org/en/strict/#toc-enabling-flow-strict-in-a-flowconfig)

 Comments
--------

 Comment support was added in v0.23.0. Lines beginning with zero or more spaces followed by an `#` or `;` or `💩` are ignored. For example:

 
```
# This is a comment
  # This is a comment
; This is a comment
  ; This is a comment
💩 This is a comment
  💩 This is a comment
```
 Where to put the `.flowconfig`
------------------------------

 The location of the `.flowconfig` is significant. Flow treats the directory that contains the `.flowconfig` as the *project root*. By default Flow includes all the source code under the project root. The paths in the [[include] section](include) are relative to the project root. Some other configuration also lets you reference the project root via the macro `<PROJECT_ROOT>`.

 Most people put the `.flowconfig` in the root of their project (i.e. next to the `package.json`). Some people put all their code in a `src/` directory and therefore put the `.flowconfig` at `src/.flowconfig`.

 Example
-------

 Say you have the following directory structure, with your `.flowconfig` in `mydir`:

 
```
otherdir
└── src
    ├── othercode.js
mydir
├── .flowconfig
├── build
│   ├── first.js
│   └── shim.js
├── lib
│   └── flow
├── node_modules
│   └── es6-shim
└── src
    ├── first.js
    └── shim.js
```
 Here is an example of how you could use the `.flowconfig` directives.

 
```
[include]
../otherdir/src

[ignore]
.*/build/.*

[libs]
./lib
```
 Now `flow` will include a directory outside the `.flowconfig` path in its check, ignore the `build` directory and use the declarations in `lib`.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/config>

Types & Expressions
===================

 In JavaScript there are many types of values: numbers, strings, booleans, functions, objects, and more.

 
```
(1234: number);
("hi": string);
(true: boolean);
([1, 2]: Array<number>);
({ prop: "value" }: Object);
(function method() {}: Function);

```
 These values can be used in many different ways:

 
```
1 + 2;
"foo" + "bar";
!true;
[1, 2].push(3);
let value = obj.prop;
obj.prop = "value";
method("value");

```
 All of these different expressions create a new type which is a result of the types of values and the operations run on them.

 
```
let num: number = 1 + 2;
let str: string = "foo" + "bar";

```
 In Flow every value and expression has a type.

 Figuring out types statically
-----------------------------

 Flow needs a way to be able to figure out the type of every expression. But it can’t just run your code to figure it out, if it did it would be affected by any issues that your code has. For example, if you created an infinite loop Flow would wait for it to finish forever.

 Instead, Flow needs to be able to figure out the type of a value by analyzing it without running it (static analysis). It works its way through every known type and starts to figure out what all the expressions around them result in.

 For example, to figure out the result of the following expression, Flow needs to figure out what its values are first.

 
```
val1 + val2;

```
 If the values are numbers, then the expression results in a number. If the values are strings, then the expression results in a string. There are a number of different possibilities here, so Flow must look up what the values are.

 If Flow is unable to figure out what the exact type is for each value, Flow must figure out what every possible value is and check to make sure that the code around it will still work with all of the possible types.

 Soundness and Completeness
--------------------------

 When you run your code, a single expression will only be run with a limited set of values. But still Flow checks *every* possible value. In this way Flow is checking too many things or *over-approximating* what will be valid code.

 By checking every possible value, Flow might catch errors that will not actually occur when the code is run. Flow does this in order to be *“sound”*.

 In type systems, ***soundness*** is the ability for a type checker to catch every single error that *might* happen at runtime. This comes at the cost of sometimes catching errors that will not actually happen at runtime.

 On the flip-side, ***completeness*** is the ability for a type checker to only ever catch errors that *would* happen at runtime. This comes at the cost of sometimes missing errors that will happen at runtime.

 In an ideal world, every type checker would be both sound *and* complete so that it catches *every* error that *will* happen at runtime.

 Flow tries to be as sound and complete as possible. But because JavaScript was not designed around a type system, Flow sometimes has to make a tradeoff. When this happens Flow tends to favor soundness over completeness, ensuring that code doesn’t have any bugs.

 Soundness is fine as long as Flow isn’t being too noisy and preventing you from being productive. Sometimes when soundness would get in your way too much, Flow will favor completeness instead. There’s only a handful of cases where Flow does this.

 Other type systems will favor completeness instead, only reporting real errors in favor of possibly missing errors. Unit/Integration testing is an extreme form of this approach. Often this comes at the cost of missing the errors that are the most complicated to find, leaving that part up to the developer.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/lang/types-and-expressions>

Usage
=====

 Once you have [installed](https://flow.org/en/install/) Flow, you will want to get a feel of how to use Flow at the most basic level. For most new Flow projects, you will follow this general pattern:

 * [Initialize your project](#toc-initialize-your-project) with `flow init`.
* Start the [Flow background process](#toc-run-the-flow-background-process) with `flow`.
* [Determine](#toc-prepare-your-code-for-flow) which files Flow will monitor with `// @flow`.
* [Write Flow code](#toc-write-flow-code) for your project.
* [Check your code](#toc-check-your-code) for type errors.

 Initialize Your Project
-----------------------

 Preparing a project for Flow requires only one command:

 
```
flow init
```
 Run this command at the top level of your project to create one, empty file called [`.flowconfig`](https://flow.org/en/config/). At its most basic level, `.flowconfig` tells the Flow background process the root of where to begin checking Flow code for errors.

 And that is it. Your project is now Flow-enabled.

 
>  It is common to have an empty `.flowconfig` file for your project. However, you can [configure and customize Flow](https://flow.org/en/config/) in many ways through options available to be added to `.flowconfig`.
> 
>  

 Run the Flow Background Process
-------------------------------

 The core benefit to Flow is its ability to quickly check your code for errors. Once you have enabled your project for Flow, you can start the process that allows Flow to check your code incrementally and with great speed.

 
```
flow status
```
 This command first starts a background process that will check all [Flow files](#toc-prepare-your-code-for-flow) for errors. The background process continues running, monitoring changes to your code and checking those changes incrementally for errors.

 
>  You can also type `flow` to accomplish the same effect as `status` is the default flag to the `flow` binary.
> 
>  

 
>  Only one background process will be running at any given time, so if you run `flow status` multiple times, it will use the same process.
> 
>  

 
>  To stop the background process, run `flow stop`.
> 
>  

 Prepare Your Code for Flow
--------------------------

 The Flow background process monitors all Flow files. However, how does it know which files are Flow files and, thus, should be checked? Placing the following **before any code** in a JavaScript file is the flag the process uses to answer that question.

 
```
// @flow

```
 This flag is in the form of a normal JavaScript comment annotated with `@flow`. The Flow background process gathers all the files with this flag and uses the type information available from all of these files to ensure consistency and error free programming.

 
>  You can also use the form `/* @flow */` for the flag as well.
> 
>  

 
>  For files in your project without this flag, the Flow background process skips and ignores the code (unless you call `flow check --all`, which is beyond the scope of basic usage).
> 
>  

 Write Flow Code
---------------

 Now that all the setup and initialization is complete, you are ready to write actual Flow code. For each file that you have flagged with `// @flow`, you now have the full power of Flow and its type-checking available to you. Here is an example Flow file:

 
```
// @flow

function foo(x: ?number): string {
  if (x) {
    return x;
  }
  return "default string";
}

```
 Notice the types added to the parameter of the function along with a return type at the end of the function. You might be able to tell from looking at this code that there is an error in the return type since the function can also return a `number`. However, you do not need to visually inspect the code since the Flow background process will be able to catch this error for you when you [check your code](#toc-check-your-code).

 Check Your Code
---------------

 The great thing about Flow is that you can get near real-time feedback on the state of your code. At any point that you want to check for errors, just run:

 
```
# equivalent to `flow status`
flow
```
 The first time this is run, the [Flow background process](#toc-run-flow-background-process) will be spawned and all of your Flow files will be checked. Then, as you continue to iterate on your project, the background process will continuously monitor your code such that when you run `flow` again, the updated result will be near instantaneous.

 For the [code above](#toc-write-flow-code), running `flow` will yield:

 
```
test.js:5
  5:     return x;
                ^ number. This type is incompatible with the expected return type of
  3: function foo(x: ?number): string {
                               ^^^^^^ string
```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/usage>

Lazy Modes
==========

 By default, the Flow server will typecheck all your code. This way it can answer questions like “are there any Flow errors anywhere in my code”. This is very useful for tooling, like a continuous integration hook which prevents code changes which introduce Flow errors.

 However, sometimes a Flow user might not care about all the code. If they are editing a file `foo.js`, they might only want Flow to typecheck the subset of the repository needed to answer questions about `foo.js`. Since Flow would only check a smaller number of files, this would be faster. This is the motivation behind Flow’s lazy mode.

 Classifying Files
-----------------

 Lazy mode classifes your code into four categories:

 1. **Focused files**. These are the files which the user cares about.
2. **Dependent files**. These are the files which depend on the focused files. Changes to the focused files might cause type errors in the dependent files.
3. **Dependency files**. These are the files which are needed in order to typecheck the focused or dependent files.
4. **Unchecked files**. All other files.

 Lazy mode will still find all the JavaScript files and parse them. But it won’t typecheck the unchecked files.

 Choosing Focused Files
----------------------

 Focused files are all of the files that have changed in one of the following ways.

 Flow will focus files when they change on disk, using Flow’s built-in file watcher (“dfind”) or Watchman.

 So, all files that change while Flow is running will be focused. But what about files that change when Flow is not running? If you’re using Git or Mercurial, Flow will ask it for all of the files that have changed since the mergebase with “master” (the common ancestor of the current commit and the master branch).

 If you’re not using “master” (e.g. “main” instead), you can change this with the `file_watcher.mergebase_with` config. If you’re working from a clone, you might want to set this to “origin/master” (for Git), which will focus all files that have changed locally, even if you commit to your local “master” branch.

 The net result is that Flow will find the same errors in lazy mode as in a full check, so long as there are no errors upstream. For example, if your CI ensures that there are no errors in “master,” then it’s redundant for Flow to check all of the unchanged files for errors that can’t exist.

 Using Lazy Mode
---------------

 To enable lazy mode, set `lazy_mode=true` in the `.flowconfig`.

 To start a Flow server in lazy mode manually, run

 
```
flow server --lazy-mode true
```
 Forcing Flow to Treat a File as Focused
---------------------------------------

 You can force Flow to treat one or more files as focused from the CLI.

 
```
flow force-recheck --focus ./path/to/A.js /path/to/B.js
```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/lang/lazy-modes>

Constrained Writes
==================

 As of Flow v0.186.0, unannotated variables will be inferred to have a precise type by their initializer or initial assignment, and all subsequent assignments to that variable will be constrained by this type. This page shows some examples of how Flow determines what type an unannotated variable is inferred to have.

 **If you want a variable to have a different type than what Flow infers for it, you can always add a type annotation to the variable’s declaration. That will override everything discussed in this page!**

 Variables initialized at their declarations
-------------------------------------------

 The common case for unannotated variables is very straightforward: when a variable is declared with an initializer that is not the literal `null`, that variable will from then on have the type of the initializer, and future writes to the variable will be constrained by that type [(try flow)](https://flow.org/try/#0JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwBQdMAnmFnAArFjoC8cA3gB84YLgC44IYAA8sAEziCAvvTpysuADbJKcAG4640iQDsAriABGWKPXVadbA1DhNTF67bUbtu5yK5UCU4IblVNLHhRCDkzfDg+AFlkGAALADpUAEdYAAppAEo4AGpXegB6crgAA2jY-Gq4VLQ4ZlYa8ysbaroI+ABhEkgTLBN4Plz+aLAlYMCingA+AThKGDMoEzgAHkWpriVt8uWlOkqawfAIEbHG5vQ2rGrsPBh0y+HRmAAVFixtkLcRY9PpwLAREBfBI7D7XKH8dKI6aoJRwY5wM5VargrCQ25NFqPGovfDpACiEK+2xJb1hNx+fwBgUWwKAA):

 
```
let product = Math.sqrt(x) * y;
// `product` has type `number`
let Component = ({prop}: Props) => { return <>{prop}</> }
// `Component` has type`React.ComponentType<Props>`
let element = <Component {...props} />
// `element` has type `React.Element<React.ComponentType<Props>>`

```
 Any subsequent assignments to `product`, `Component`, or `element` will be checked against the types that Flow infers for the initializers, and if conflicting types are assigned, Flow will signal an error [(try flow)](https://flow.org/try/#0JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwBQdMAnmFnAArFjoC8cA3gB84YLgC44IYAA8sAEziCAvvTpysuADbJKcAG4640iQDsAriABGWKPXVadbA1DhNTF67bUbtu5yK5UCU4IblVNLHhRCDkzfDg+AFlkGAALADpUAEdYAAppAEo4AGpXegB6crgAA2jY-Gq4VLQ4ZlYa8ysbaroI+ABhEkgTLBN4Plz+aLAlYMCingA+AThKGDMoEzgAHkWpriVt8uWlOkqawfAIEbHG5vQ2rGrsPBh0y+HRmAAVFixtkLcRY9PpwLAREBfBI7D7XKH8dKI6aoJRwY5wM5VargrCQ25NFqPGovfDpACiEK+2xJb1hNx+fwBgUWwIYRIA8mkbIDeAJhBAuVAAPrTCRSWQKZR2HyOfSGTmpGx0r4SXIK7nzBLLGnpAByMSw0ocfkMAsVwuREnVUB5DHO+pgbDSKTguVwG0oY00TCKMCgTAAtARNBAAO5wOQQLCoExkeDNPROxVwEbh6wJ4DQOAQAhwMwmZAmEwClLyOVQYDISwRVCYsEF6vyAA0cFQEDgwHgkejsfgqCwSejbBaNmIUFQ6TodTi4zgACJ2RsU1hw9P4sAJ4i5zQ0VUyVAx3RlWNoZMzTYRQcrYKeQtlvxVpENltdvxzxaDkcTjvzvvDzi8VnbZrWPeAEURd9L1CFE0UWH89wPaAgA):

 
```
product = "Our new product is..."; // Error
Component = ({other_prop}: OtherProps) => { return <>{other_prop}</> }; // Error
element = <OtherComponent {...other_props} />; // Error

```
 If you want these examples to typecheck, and for Flow to realize that different kinds of values can be written to these variables, you must add a type annotation reflecting this more general type to their declarations [(try flow)](https://flow.org/try/#0JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwBQdMAnmFnAArFjoC8cA3gB84YLgC44IYAA8sAEziCAvvTpysuADbJKcAG4640iQDsAriABGWKPXVadbA1DhNTF67bUbtu5yK5UCU4IblVNLHhRCDkzfHcrG0U4VBgoYBMAczg+AFlkGAALADpUAEdYAAppAEo4AGpXcMi4AGESSBMsExgJKVkFPkr+aLAlYMC6ngA+AThKGDMoEzgAHmmRriVVgHpZpTodnbgAOQg4TIgYuGZWG-PKUSxUbvgi4FQAQkxntLjF3S4GJsDKpHByBgReBYCIgV4SbB4GDFM7qHJraa7WYMRgsNgAeSKNhC3HRQjgECJUAA+qM+jJ5IoVN4HH5DITCjZ2uAIF0ehJKhziZMcrNEfgUcC7D5HPpDJTOTTRkE4EKoCTUAxorF8OiAET4pZwLoAdwCMX+cA+xRtevo3M6r3RwwVNlpWwkao1U1m-HmkSWK3W-FdSq2WLgKjgdBhWDhPXRqzVDt5Tv4NuKofdoVQSjgexocCAA):

 
```
let product: number | string = ...
let Component: mixed = ... // No good type to represent this! Consider restructuring
let element: React.Node = ...

```
 Variables declared without initializers
---------------------------------------

 Often variables are declared without initializers. In such cases, Flow will try to choose the “first” assignment or assignments to the variable to define its type. “First” here means both top-to-bottom and nearer-scope to deeper-scope—we’ll try to choose an assignment that happens in the same function scope as the variable’s declaration, and only look inside nested functions if we don’t find any assignments locally [(try flow)](https://flow.org/try/#0DYUwLgBGD2AOAyIBuJgEEDOGCWBzAdiACYDcAUGQGYCu+AxmNtPhABaqwgBOAFAJQQA3mQhQ4iFOix5CRCAF4IAFgBMJCAHoNEAKJcu0LhGwtqsOtAC2J3BBRcczCNEoQAYsGgB3AFwQABjAIyKiYOATE-mwAhhhQAJ6cARhgXDb+ZAC+FEESodIRcooARAASqJ4QXobARMXqWhAAKqzYcV5pYCAQRODc1oRxYOx20VwA5EOJIGS5IVLhsgpQXNQgDdp6BkYmEGYWA7b2jiwu7p6+AXOSYTKRMVNJ-ilp+Lj+QA).

 
```
let topLevelAssigned;

function helper() {
  topLevelAssigned = 42; // Error: `topLevelAssigned` has type `string`
}

topLevelAssigned = "Hello world"; // This write determines the var's type
topLevelAssigned = true; // Error: `topLevelAssigned` has type `string`

```
 If there are two or more possible “first assignments,” due to an if or switch statement, they’ll both count—this is one of the few ways that Flow will still infer unions for variable types [(try flow)](https://flow.org/try/#0CYUwxgNghgTiAEA3W8wHsB2wCWAXbmAXPAEZpoQhQYDcAUHZbvALYCeAcgK4skgwB5GAGVcMbBgDm9OtgBm8ABToseAhgCU8AN514rTjz6CRYiZPgBeeABYATPQC+8EBADOCXfvbde-IaLiUlbwAEQAEq4QaPAA7mgwEMChTgw+Rv6mQRbWdgCMNPAA9EXwchIgdOl+JoHmIaEA4uTAJGwgKcWl5RiV1cYBZsHWclDuIIUl8ACiMDAJ8BLwXAAO6Cz1iPxu6vBoCgBi0bHEAAb9mXVSp-AAFlBu8LhsKwinGBkw8AA+8G5DklOQA):

 
```
let myNumberOrString;

if (condition) {
  myNumberOrString = 42; // Determines type
} else {
  myNumberOrString = "Hello world"; // Determines type
}

myNumberOrString = 21; // fine, compatible with type
myNumberOrString = "Goodbye"; // fine, compatible with type
myNumberOrString = false; // Error: `myNumberOrString` has type `number | string`

```
 This only applies when the variable is written to in both branches, however. If only one branch contains a write, that write becomes the type of the variable afterwards (though Flow will still check to make sure that the variable is definitely initialized) [(try flow)](https://flow.org/try/#0CYUwxgNghgTiAEA3W8wHsB2wCWAXbmAXPAEZpoQhQYDcAUHZbvJiAEIzVgAWAggM79sAcwwhg9OtgBm8ABToseAhgCU8AN514LMRy59BIscHgBeeACIAEiAgQ08AO5oYEYAEJL9AL4NW+hg8AkKi4gB0uGgAqgAOsSAwAMJQ-CByqjTwAPTZ8ACiMDCuxAAGAZxBhqEmpfAAtlAAnqQIAK4Y2J34UBDYAF7idBUGIcbi5vAALABMWbkFRa7wXfBtsej1XcJIiUKYLLIAYg5OZSNVY2HAddyp8LhNCfCl-Lgw26VAA):

 
```
let oneBranchAssigned;

if (condition) {
  oneBranchAssigned = "Hello world!";
}

oneBranchAssigned.toUpperCase(); // Error: `oneBranchAssigned` may be uninitialized
oneBranchAssigned = 42; // Error: `oneBranchAssigned` has type `string`

```
 Variables initialized to `null`
-------------------------------

 Finally, the one exception to the general principle that variable’s types are determined by their first assignment(s) is when a variable is initialized as (or whose first assignment is) the literal value `null`. In such cases, the *next* non-null assignment (using the same rules as above) determines the rest of the variable’s type, and the overall type of the variable becomes a union of `null` and the type of the subsequent assignment. This supports the common pattern where a variable starts off as `null` before getting assigned by a value of some other type [(try flow)](https://flow.org/try/#0GYVwdgxgLglg9mABMGYAmBJAIgNQIYA2IApgDwAqAfABRozQBciA3gNoDWxAnkwM5QAnVAHMAuk3IBfAJQSWAKESICxKIhhp8BRAF5EYEAQIBuRAHoz6sDFiEYAL2JpEeXogAGBo+8XI4AxGoIBH5ETi4rRDpoaQUlJRhgQPDdHT0Acmx02OZfePVNQl0o+igOblFTC0QMMGBiAKgACzw1dw0td0QWtyguAAdiDy9tAB9Ech98yV8ZhKTqDqK0vRGcvMRmgTgAd31iPYBRAW2BagAiADk4RGIwQQjgfxqsAEJz6WNZ3wFVEAEkEsTPJJEA).

 
```
function findIDValue<T>(dict: {[key: string]: T}): T {
  let idVal = null; // initialized as `null`
  for (const key in dict) {
    if (key === 'ID') {
      idVal = dict[key]; // Infer that `idVal` has type `null | T`
    }
  }
  if (idVal === null) {
    throw new Error("No entry for ID!");
  }
  return idVal;
}

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/lang/constrained-writes>

Type Refinements
================

 Refinements are a frequently used aspect of many type systems. They are so ingrained in the way that we program and even the way that we think you might not even notice them.

 In the code below, value can either be `"A"` or `"B"`.

 
```
// @flow
function method(value: "A" | "B") {
  if (value === "A") {
    // value is "A"
  }
}

```
 Inside of the if block we know that value must be `"A"` because that’s the only time the if-statement will be truthy.

 The ability for a static type checker to be able to tell that the value inside the if statement must be `"A"` is known as a refinement.

 Next we’ll add an else block to our if statement.

 
```
// @flow
function method(value: "A" | "B") {
  if (value === "A") {
    // value is "A"
  } else {
    // value is "B"
  }
}

```
 Inside of the else block we know that value must be `"B"` because it can only be `"A"` or `"B"` and we’ve removed `"A"` from the possibilities.

 You can expand this even further and keep refining possibilities away:

 
```
// @flow
function method(value: "A" | "B" | "C" | "D") {
  if (value === "A") {
    // value is "A"
  } else if (value === "B") {
    // value is "B"
  } else if (value === "C") {
    // value is "C"
  } else {
    // value is "D"
  }
}

```
 Refinements can also come in other forms other than testing for equality:

 
```
// @flow
function method(value: boolean | Array<string> | Event) {
  if (typeof value === "boolean") {
    // value is a boolean
  } else if (Array.isArray(value)) {
    // value is an Array
  } else if (value instanceof Event) {
    // value is an Event
  }
}

```
 Or you could refine on the shape of objects.

 
```
// @flow
type A = { type: "A" };
type B = { type: "B" };

function method(value: A | B) {
  if (value.type === "A") {
    // value is A
  } else {
    // value is B
  }
}

```
 Which also applies to nested types within objects.

 
```
// @flow
function method(value: { prop?: string }) {
  if (value.prop) {
    value.prop.charAt(0);
  }
}

```
 Refinement Invalidations
------------------------

 It is also possible to invalidate refinements, for example:

 
```
// @flow
function otherMethod() { /* ... */ }

function method(value: { prop?: string }) {
  if (value.prop) {
    otherMethod();
    // $ExpectError
    value.prop.charAt(0);
  }
}

```
 The reason for this is that we don’t know that `otherMethod()` hasn’t done something to our value. Imagine the following scenario:

 
```
// @flow
var obj = { prop: "test" };

function otherMethod() {
  if (Math.random() > 0.5) {
    delete obj.prop;
  }
}

function method(value: { prop?: string }) {
  if (value.prop) {
    otherMethod();
    // $ExpectError
    value.prop.charAt(0);
  }
}

method(obj);

```
 Inside of `otherMethod()` we sometimes remove `prop`. Flow doesn’t know if the `if (value.prop)` check is still true, so it invalidates the refinement.

 There’s a straightforward way to get around this. Store the value before calling another method and use the stored value instead. This way you can prevent the refinement from invalidating.

 
```
// @flow
function otherMethod() { /* ... */ }

function method(value: { prop?: string }) {
  if (value.prop) {
    var prop = value.prop;
    otherMethod();
    prop.charAt(0);
  }
}

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/lang/refinements>

Enabling enums in your project
==============================

 Upgrade tooling
---------------

 To enable Flow Enums in your repo, you must first update the following packages:

 * Upgrade to at least Flow 0.159
	+ Flow needs to have some configuration set to enable enums - see below.
* Upgrade [Prettier](https://prettier.io/) to at least version 2.2
	+ As of that version, Prettier can handle parsing and pretty printing Flow Enums out of the box.
	+ You must use the `flow` [parser option](https://prettier.io/docs/en/options.html#parser) for JavaScript files to be able to format Flow Enums.
* Upgrade [Babel](https://babeljs.io/) to at least version 7.13.0
	+ As of that version, Babel can parse Flow Enums. However, to enable this parsing some configuration needs to be supplied, and additionally it does not include the transform required - see below.
* Upgrade [jscodeshift](https://github.com/facebook/jscodeshift) to at least version 0.11.0
* Upgrade [hermes-parser](https://www.npmjs.com/package/hermes-parser) to at least version 0.4.8
* For ESLint, either:
	+ Use [hermes-eslint](https://www.npmjs.com/package/hermes-eslint) as your ESLint parser, at least version 0.4.8
	+ Or upgrade [babel-eslint](https://github.com/babel/babel-eslint) to version 10.1.0
		- As of that version, `babel-eslint` can handle Flow Enums out of the box.
		- Do not upgrade to 11.x, this branch does not support Flow Enums.
	+ Or use another solution using Babel 7.13.0 or later, with Flow enabled - this may also work

 If you have any other tool which examines your code, you need to update it as well. If it uses [flow-parser](https://www.npmjs.com/package/flow-parser), [hermes-parser](https://www.npmjs.com/package/hermes-parser) or `@babel/parser`, upgrade those as per the instructions above. If it uses some other parser, you will need to implement parsing Flow Enums in that parser. You can look at the existing code in Babel, Flow, and Hermes parsers to guide your work.

 Enable enums
------------

 * In your `.flowconfig`, under the `[options]` heading, add `enums=true`
* Add the Flow Enums Babel transform. It turns enum declaration AST nodes into calls to the runtime: [babel-plugin-transform-flow-enums](https://www.npmjs.com/package/babel-plugin-transform-flow-enums). Add it to your development dependencies and adjust your Babel configuration to use the transform. The transform by default requires the runtime package directly (below), but you can configure this.
* Add the Flow Enum runtime package to your production dependencies. This will be required and used at runtime to create Flow Enums: [flow-enums-runtime](https://www.npmjs.com/package/flow-enums-runtime)

 Enable suggested ESLint rules
-----------------------------

 Enums can be exhaustively checked in `switch` statements, so may increase the use of `switch` statements compared to before. To prevent common issues with `switch` statements, we suggest you enable these ESLint rules (at least as warnings):

 * [no-fallthrough](https://eslint.org/docs/rules/no-fallthrough): This prevents the user from accidentally forgetting a `break` statement at the end of their switch case, while supporting common use-cases.
* [no-case-declarations](https://eslint.org/docs/rules/no-case-declarations): This prevents lexicaly scoped declarations (`let`, `const`) from being introduced in a switch case, without wrapping that case in a new block. Otherwise, declarations in different cases could conflict.

 We also have some Flow Enums specific rules as part of [eslint-plugin-fb-flow](https://www.npmjs.com/package/eslint-plugin-fb-flow):

 * [use-flow-enums](https://www.npmjs.com/package/eslint-plugin-fb-flow#use-flow-enums): Suggests that enum-like `Object.freeze` and `keyMirror` usage be turned into Flow Enums instead.
* [flow-enums-default-if-possible](https://www.npmjs.com/package/eslint-plugin-fb-flow#flow-enums-default-if-possible): Auto-fixes string enums with specified values identical to the member names to defaulted enums.
* [no-flow-enums-object-mapping](https://www.npmjs.com/package/eslint-plugin-fb-flow#no-flow-enums-object-mapping): Suggests using a function with a switch to map enum values to other values, instead of an object literal.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/enums/enabling-enums>

Subsets & Subtypes
==================

 What is a subtype?
------------------

 A type like `number`, `boolean`, or `string` describes a set of possible values. A `number` describes every possible number, so a single number (such as `42`) would be a *subtype* of the `number` type. Conversely, `number` would be a *supertype* of the type `42`.

 If we want to know whether one type is the subtype of another, we need to look at all the possible values for both types and figure out if the other has a *subset* of the values.

 For example, if we had a `TypeA` which described the numbers 1 through 3, and a `TypeB` which described the numbers 1 through 5: `TypeA` would be considered a *subtype* of `TypeB`, because `TypeA` is a subset of `TypeB`.

 
```
type TypeA = 1 | 2 | 3;
type TypeB = 1 | 2 | 3 | 4 | 5;

```
 Consider a `TypeLetters` which described the strings: “A”, “B”, “C”, and a `TypeNumbers` which described the numbers: 1, 2, 3. Neither of them would be a subtype of the other, as they each contain a completely different set of values.

 
```
type TypeLetters = "A" | "B" | "C";
type TypeNumbers =  1  |  2  |  3;

```
 Finally, if we had a `TypeA` which described the numbers 1 through 3, and a `TypeB` which described the numbers 3 through 5. Neither of them would be a subtype of the other. Even though they both have 3 and describe numbers, they each have some unique items.

 
```
type TypeA = 1 | 2 | 3;
type TypeB = 3 | 4 | 5;

```
 When are subtypes used?
-----------------------

 Most of the work that Flow does is comparing types against one another.

 For example, in order to know if you are calling a function correctly, Flow needs to compare the arguments you are passing with the parameters the function expects.

 This often means figuring out if the value you are passing in is a subtype of the value you are expecting.

 So if I write a function that expects the numbers 1 through 5, any subtype of that set will be acceptable.

 
```
// @flow
function f(param: 1 | 2 | 3 | 4 | 5) {
  // ...
}

declare var oneOrTwo: 1 |  2; // Subset of the input parameters type.
declare var fiveOrSix: 5 | 6; // Not a subset of the input parameters type.

f(oneOrTwo); // Works!
// $ExpectError
f(fiveOrSix); // Error!

```
 Subtypes of complex types
-------------------------

 Flow needs to compare more than just sets of primitive values, it also needs to be able to compare objects, functions, and every other type that appears in the language.

 ### Subtypes of objects

 You can start to compare two objects by their keys. If one object contains all the keys of another object, then it may be a subtype.

 For example, if we had an `ObjectA` which contained the key `foo`, and an `ObjectB` which contained the keys `foo` and `bar`. Then it’s possible that `ObjectB` is a subtype of `ObjectA`.

 
```
// @flow
type ObjectA = { foo: string };
type ObjectB = { foo: string, bar: number };

let objectB: ObjectB = { foo: 'test', bar: 42 };
let objectA: ObjectA = objectB; // Works!

```
 But we also need to compare the types of the values. If both objects had a key `foo` but one was a `number` and the other was a `string`, then one would not be the subtype of the other.

 
```
// @flow
type ObjectA = { foo: string };
type ObjectB = { foo: number, bar: number };

let objectB: ObjectB = { foo: 1, bar: 2 };
// $ExpectError
let objectA: ObjectA = objectB; // Error!

```
 If these values on the object happen to be other objects, we would have to compare those against one another. We need to compare every value recursively until we can decide if we have a subtype or not.

 ### Subtypes of functions

 Subtyping rules for functions are more complicated. So far, we’ve seen that `A` is a subtype of `B` if `B` contains all possible values for `A`. For functions, it’s not clear how this relationship would apply. To simplify things, you can think of a function type `A` as being a subtype of a function type `B` if functions of type `A` can be used wherever a function of type `B` is expected.

 Let’s say we have a function type and a few functions. Which of the functions can be used safely in code that expects the given function type?

 
```
type FuncType = (1 | 2) => "A" | "B";

let f1: (1 | 2) => "A" | "B" | "C" = (x) => /* ... */
let f2: (1 | null) => "A" | "B" = (x) => /* ... */
let f3: (1 | 2 | 3) => "A" = (x) => /* ... */

```
 * `f1` can return a value that `FuncType` never does, so code that relies on `FuncType` might not be safe if `f1` is used. Its type is not a subtype of `FuncType`.
* `f2` can’t handle all the argument values that `FuncType` does, so code that relies on `FuncType` can’t safely use `f2`. Its type is also not a subtype of `FuncType`.
* `f3` can accept all the argument values that `FuncType` does, and only returns values that `FuncType` does, so its type is a subtype of `FuncType`.

 In general, the function subtyping rule is this: A function type `B` is a subtype of a function type `A` if and only if `B`’s inputs are a superset of `A`’s, and `B`’s outputs are a subset of `A`’s. The subtype must accept *at least* the same inputs as its parent, and must return *at most* the same outputs.

 The decision of which direction to apply the subtyping rule on inputs and outputs is governed by variance, which is the topic of the next section.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/lang/subtypes>

Nominal & Structural Typing
===========================

 An important attribute of every type system is whether they are structural or nominal, they can even be mixed within a single type system. So it’s important to know the difference.

 A type is something like a string, a boolean, an object, or a class. They have names and they have structures. Primitives like strings or booleans have a very simple structure and only go by one name.

 More complex types like object or classes have more complex structures. They each get their own name even if they sometimes have the same structure overall.

 A static type checker uses either the names or the structure of the types in order to compare them against other types. Checking against the name is nominal typing and checking against the structure is structural typing.

 ### Nominal typing

 Languages like C++, Java, and Swift have primarily nominal type systems.

 
```
class Foo { method(input: string) { /* ... */ } }
class Bar { method(input: string) { /* ... */ } }

let foo: Foo = new Bar(); // Error!

```
 Here you can see a pseudo-example of a nominal type system erroring out when you’re trying to put a `Bar` where a `Foo` is required because they have different names.

 ### Structural typing

 Languages like OCaml, Haskell, and Elm have primarily structural type systems.

 
```
class Foo { method(input: string) { /* ... */ } }
class Bar { method(input: string) { /* ... */ } }

let foo: Foo = new Bar(); // Works!

```
 Here you can see a pseudo-example of a structural type system passing when you’re trying to put a Bar where a `Foo` is required because their structure is exactly the same.

 But as soon as you change the shape it will start to cause errors.

 
```
class Foo { method(input: string) { /* ... */ } }
class Bar { method(input: number) { /* ... */ } }

let foo: Foo = new Bar(); // Error!

```
 It can get a little bit more complicated than this.

 We’ve demonstrated both nominal and structure typing of classes, but there are also other complex types like objects and functions which can also be either nominal or structural. Even further, they can be different within the same type system (most of the languages listed before has features of both).

 For example, Flow uses structural typing for objects and functions, but nominal typing for classes.

 #### Functions are structurally typed

 When comparing a function type with a function it must have the same structure in order to be considered valid.

 
```
// @flow
type FuncType = (input: string) => void;
function func(input: string) { /* ... */ }
let test: FuncType = func; // Works!

```
 #### Objects are structurally typed

 When comparing an object type with an object it must have the same structure in order to be considered valid.

 
```
type ObjType = { property: string };
let obj = { property: "value" };
let test: ObjType = obj;

```
 #### Classes are nominally typed

 When you have two classes with the same structure, they still are not considered equivalent because Flow uses nominal typing for classes.

 
```
// @flow
class Foo { method(input: string) { /* ... */ } }
class Bar { method(input: string) { /* ... */ } }
let test: Foo = new Bar(); // Error!

```
 If you wanted to use a class structurally you could do that using an interface:

 
```
interface Interface {
  method(value: string): void;
};

class Foo { method(input: string) { /* ... */ } }
class Bar { method(input: string) { /* ... */ } }

let test1: Interface = new Foo(); // Okay.
let test2: Interface = new Bar(); // Okay.

```
 ### Mixing nominal and structural typing

 The design decision in Flow around mixing nominal and structural typing was chosen based on how objects, functions, and classes are already used in JavaScript.

 The JavaScript language is a bunch of object-oriented ideas and functional ideas mixed together. Developer’s usage of JavaScript tends to be mixed as well. Classes (or constructor functions) being the more object-oriented side and functions (as lambdas) and objects tend to be more on the functional side, developers use both simultaneously.

 When someone writes a class, they are declaring a *thing*. This thing might have the same structure as something else but they still serve different purposes. Imagine two component classes that both have `render()` methods, these components could still have totally different purposes, but in a structural type system they’d be considered exactly the same.

 Flow chooses what is natural for JavaScript, and should behave the way you expect it to.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/lang/nominal-structural>

Depth Subtyping
===============

 Assume we have two classes, which have a subtype relationship:

 
```
class Person { name: string }
class Employee extends Person { department: string }

```
 It’s valid to use an `Employee` instance where a `Person` instance is expected.

 
```
// @flow
class Person { name: string }
class Employee extends Person { department: string }

var employee: Employee = new Employee;
var person: Person = employee; // OK

```
 However, it is not valid to use an object containing an `Employee` instance where an object containing a `Person` instance is expected.

 
```
// @flow
class Person { name: string }
class Employee extends Person { department: string }

var employee: { who: Employee } = { who: new Employee };
// $ExpectError
var person: { who: Person } = employee; // Error

```
 This is an error because objects are mutable. The value referenced by the `employee` variable is the same as the value referenced by the `person` variable.

 
```
person.who = new Person;

```
 If we write into the `who` property of the `person` object, we’ve also changed the value of `employee.who`, which is explicitly annotated to be an `Employee` instance.

 If we prevented any code from ever writing a new value to the object through the `person` variable, it would be safe to use the `employee` variable. Flow provides a syntax for this:

 
```
// @flow
class Person { name: string }
class Employee extends Person { department: string }

var employee: { who: Employee } = { who: new Employee };
var person: { +who: Person } = employee; // OK
// $ExpectError
person.who = new Person; // Error!

```
 The plus sign indicates that the `who` property is “covariant.” Using a covariant property allows us to use objects which have subtype-compatible values for that property. By default, object properties are invariant, which allow both reads and writes, but are more restrictive in the values they accept.

 Read more about [property variance](variance).



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/lang/depth-subtyping>

Types-First
===========

 Flow checks codebases by processing each file separately in dependency order. After a file has been checked, a signature is extracted and stored in main memory, to be used for files that depend on it. Currently, the default mode (we’ll also refer to it as *classic* mode) builds these signatures by using the types inferred for the file’s exports. In the new *types-first* architecture, Flow relies on annotations available at the boundaries of files to build these signatures.

 The benefit of this new architecture is dual:

 1. It dramatically improves *performance*, in particular when it comes to rechecks. Suppose we want Flow to check a file `foo.js`, for which it hasn’t checked its dependencies yet. Classic mode would need to check all dependencies and generate signatures from them first, before it could check `foo.js`. In types-first, Flow extracts the dependency signatures just by looking at the annotations around the exports. This process is mostly syntactic, and therefore much faster than full type inference.
2. It improves error *reliability*. Inferred types often become complicated, and may lead to errors being reported in downstream files, far away from their actual source. Type annotations at file boundaries of files can help localize such errors, and address them in the file that introduced them.

 The caveat of this new version is that it requires exported parts of the code to be annotated with types, or to be expressions whose type can be trivially inferred (for example numbers and strings).

 How to upgrade your codebase to Types-First
-------------------------------------------

 ### Upgrade Flow version

 Types-first mode is officially released with version 0.125, but has been available in *experimental* status as of version 0.102. If you are currently on an older Flow version, you’d have to first upgrade Flow. Using the latest Flow version is the best way to benefit from the performance benefits outlined above.

 ### Prepare your codebase for Types-First

 Types-first requires annotations at module boundaries in order to build type signature for files. If these annotations are missing, then a `signature-verification-failure` is raised, and the exported type for the respective part of the code will be `any`.

 To see what types are missing to make your codebase types-first ready, add the following line to the `[options]` section of the `.flowconfig` file:

 
```
well_formed_exports=true
```
 Consider for example a file `foo.js` that exports a function call to `foo`

 
```
declare function foo<T>(x: T): T;
module.exports = foo(1);

```
 The return type of function calls is currently not trivially inferable (due to features like polymorphism, overloading etc.). Their result needs to be annotated and so you’d see the following error:

 
```
Cannot build a typed interface for this module. You should annotate the exports
of this module with types. Cannot determine the type of this call expression. Please
provide an annotation, e.g., by adding a type cast around this expression.
(`signature-verification-failure`)

   4│ module.exports = foo(1);
                       ^^^^^^
```
 To resolve this, you can add an annotation like the following:

 
```
declare function foo<T>(x: T): T;
module.exports = (foo(1): number);

```
 
>  Note: As of version 0.134, types-first is the default mode. This mode automatically enables `well_formed_exports`, so you would see these errors without explicitly setting this flag. It is advisable to set `types_first=false` during this part of the upgrade.
> 
>  

 #### Seal your intermediate results

 As you make progress adding types to your codebase, you can include directories so that they don’t regress as new code gets committed, and until the entire project has well-formed exports. You can do this by adding lines like the following to your .flowconfig:

 
```
well_formed_exports.includes=<PROJECT_ROOT>/path/to/directory
```
 
>  Warning: That this is a *substring* check, not a regular expression (for performance reasons).
> 
>  

 #### A codemod for large codebases

 Adding the necessary annotations to large codebases can be quite tedious. To ease this burden, we are providing a codemod based on Flow’s inference, that can be used to annotate multiple files in bulk. See [this tutorial](https://flow.org/en/cli/annotate-exports/) for more.

 ### Enable the types-first flag

 Once you have eliminated signature verification errors, you can turn on the types-first mode, by adding the following line to the `[options]` section of the `.flowconfig` file:

 
```
types_first=true
```
 You can also pass `--types-first` to the `flow check` or `flow start` commands.

 The `well_formed_exports` flag from before is implied by `types_first`. Once this process is completed and types-first has been enabled, you can remove `well_formed_exports`.

 Unfortunately, it is not possible to enable types-first mode for part of your repo; this switch affects all files managed by the current `.flowconfig`.

 
>  Note: The above flags are available in versions of Flow `>=0.102` with the `experimental.` prefix (and prior to v0.128, it used `whitelist` in place of `includes`):
> 
>  
> ```
> experimental.well_formed_exports=true
> experimental.well_formed_exports.whitelist=<PROJECT_ROOT>/path/to/directory
> experimental.types_first=true
> ```
>  

 
>  Note: If you are using a version where types-first is enabled by default (ie. `>=0.134`), make sure you set `types_first=false` in your .flowconfig while running the codemods.
> 
>  

 ### Deal with newly introduced errors

 Switching between classic and types-first mode may cause some new Flow errors, besides signature-verification failures that we mentioned earlier. These errors are due differences in the way types based on annotations are interpreted, compared to their respective inferred types.

 Below are some common error patterns and how to overcome them.

 #### Array tuples treated as regular arrays in exports

 In types-first, an array literal in an *export position*

 
```
module.exports = [e1, e2];

```
 is treated as having type `Array<t1 | t2>`, where `e1` and `e2` have types `t1` and `t2`, instead of the tuple type `[t1, t2]`.

 In classic mode, the inferred type encompassed both types at the same time. This might cause errors in importing files that expect for example to find type `t1` in the first position of the import.

 **Fix:** If a tuple type is expected, then the annotation `[t1, t2]` needs to be explicitly added on the export side.

 #### Indirect object assignments in exports

 Flow allows the code

 
```
function foo(): void {}
foo.x = () => {};
foo.x.y = 2;
module.exports = foo;

```
 but in types-first the exported type will be

 
```
{
  (): void;
  x: () => void;
}
```
 In other words it won’t take into account the update on `y`.

 **Fix:** To include the update on `y` in the exported type, the export will need to be annotated with the type

 
```
{
  (): void;
  x: { (): void; y: number; };
};
```
 The same holds for more complex assignment patterns like

 
```
function foo(): void {}
Object.assign(foo, { x: 1});
module.exports = foo;

```
 where you’ll need to manually annotate the export with `{ (): void; x: number }`, or assignments preceding the function definition

 
```
foo.x = 1;
function foo(): void {}
module.exports = foo;

```
 Note that in the last example, Flow types-first will pick up the static update if it was after the definition:

 
```
function foo(): void {}
foo.x = 1;
module.exports = foo;

```
 ### Exported variables with updates

 The types-first signature extractor will not pick up subsequent update of an exported let-bound variables. Consider the example

 
```
let foo: number | string = 1;
foo = "blah";
module.exports = foo;

```
 In classic mode the exported type would be `string`. In types-first it will be `number | string`, so if downstream typing depends on the more precise type, then you might get some errors.

 **Fix:** Introduce a new variable on the update and export that one. For example

 
```
const foo1: number | string = 1;
const foo2 = "blah";
module.exports = foo2;

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/lang/types-first>

Components
==========

 Adding Flow types to your React components is incredibly powerful. After typing your component, Flow will statically ensure that you are using the component in the way it was designed to be used.

 Early in React’s history the library provided [`PropTypes`](https://facebook.github.io/react/docs/typechecking-with-proptypes.html) which performed basic runtime checks. Flow is much more powerful as it can tell you when you are misusing a component without running your code.

 There are some Babel plugins which will generate `PropTypes` from Flow types such as [`babel-plugin-react-flow-props-to-prop-types`](https://github.com/thejameskyle/babel-plugin-react-flow-props-to-prop-types) if you want both static and runtime checks.

 Class Components
----------------

 Before we show how to type a React class component with Flow, let us first show how you would write a React class component *without* Flow but with React’s prop types. You would extend `React.Component` and add a static `propTypes` property.

 
```
import React from 'react';
import PropTypes from 'prop-types';

class MyComponent extends React.Component {
  static propTypes = {
    foo: PropTypes.number.isRequired,
    bar: PropTypes.string,
  };

  render() {
    return <div>{this.props.bar}</div>;
  }
}

```
 Now, let’s Flowify the component we just wrote:

 
```
import * as React from 'react';

type Props = {
  foo: number,
  bar?: string,
};

class MyComponent extends React.Component<Props> {
  render() {
    this.props.doesNotExist; // Error! You did not define a `doesNotExist` prop.

    return <div>{this.props.bar}</div>;
  }
}

<MyComponent foo={42} />;

```
 We removed our dependency on `prop-types` and added a Flow object type named `Props` with the same shape as the prop types but using Flow’s static type syntax. Then we passed our new `Props` type into `React.Component` as a type argument.

 Now if you try to use `<MyComponent>` with a string for `foo` instead of a number you will get an error.

 Now wherever we use `this.props` in our React component Flow will treat it as the `Props` type we defined.

 
>  **Note:** If you don’t need to use the `Props` type again you could also define it inline: `extends React.Component<{ foo: number, bar?: string }>`.
> 
>  

 
>  **Note:** We import `React` as a namespace here with `import * as React from 'react'` instead of as a default with `import React from 'react'`. When importing React as an ES module you may use either style, but importing as a namespace gives you access to React’s [utility types](../types).
> 
>  

 `React.Component<Props, State>` is a [generic type](https://flow.org/en/types/generics/) that takes two type arguments. Props and state. The second type argument, `State`, is optional. By default it is undefined so you can see in the example above we did not include `State`. We will learn more about state in the next section…

 ### Adding State

 To add a type for state to your React class component then create a new object type, in the example below we name it `State`, and pass it as the second type argument to `React.Component`.

 
```
import * as React from 'react';

type Props = { /* ... */ };

type State = {
  count: number,
};

class MyComponent extends React.Component<Props, State> {
  state = {
    count: 0,
  };

  componentDidMount() {
    setInterval(() => {
      this.setState(prevState => ({
        count: prevState.count + 1,
      }));
    }, 1000);
  }

  render() {
    return <div>Count: {this.state.count}</div>;
  }
}

<MyComponent />;

```
 In the example above we are using a [React `setState()` updater function](https://facebook.github.io/react/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous) but you could also pass a partial state object to `setState()`.

 
>  **Note:** If you don’t need to use the `State` type again you could also define it inline: `extends React.Component<{}, { count: number }>`.
> 
>  

 ### Using Default Props

 React supports the notion of `defaultProps` which you can think of as default function arguments. When you create an element and you did not include a prop with a default then React will substitute that prop with its corresponding value from `defaultProps`. Flow supports this notion as well. To type default props add a `static defaultProps` property to your class.

 
```
import * as React from 'react';

type Props = {
  foo: number, // foo is required.
  bar: string, // bar is required.
};

class MyComponent extends React.Component<Props> {
  static defaultProps = {
    foo: 42, // ...but we have a default prop for foo.
  };
}

// So we don't need to include foo.
<MyComponent bar={"abc"} />

```
 Flow will infer the type of your default props from `static defaultProps` so you don’t have to add any type annotations to use default props.

 
>  **Note:** You don’t need to make `foo` nullable in your `Props` type. Flow will make sure that `foo` is optional if you have a default prop for `foo`.
> 
>  

 If you would like to add a type annotation to `defaultProps` you can define the type as

 
```
type DefaultProps = {|
  foo: number,
|}

```
 and spread that into the `Props` type:

 
```
type Props = {
  ...DefaultProps,
  bar: string,
}

```
 This way you avoid duplicating the properties that happen to have a default value.

 Stateless Functional Components
-------------------------------

 In addition to classes, React also supports stateless functional components. You type these components like you would type a function:

 
```
import * as React from 'react';

type Props = {
  foo: number,
  bar?: string,
};

function MyComponent(props: Props) {
  props.doesNotExist; // Error! You did not define a `doesNotExist` prop.

  return <div>{props.bar}</div>;
}

<MyComponent foo={42} />

```
 ### Using Default Props for Functional Components

 React also supports default props on stateless functional components. Similarly to class components, default props for stateless functional components will work without any extra type annotations.

 
```
import * as React from 'react';

type Props = {
  foo: number, // foo is required.
};

function MyComponent(props: Props) {}

MyComponent.defaultProps = {
  foo: 42, // ...but we have a default prop for foo.
};

// So we don't need to include foo.
<MyComponent />;

```
 
>  **Note:** You don’t need to make `foo` nullable in your `Props` type. Flow will make sure that `foo` is optional if you have a default prop for `foo`.
> 
>  



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/react/components>

Type Variance
=============

 Variance is a topic that comes up fairly often in type systems and can be a bit confusing the first time you hear it. Let’s walk through each form of variance.

 First we’ll setup a couple of classes that extend one another.

 
```
class Noun {}
class City extends Noun {}
class SanFrancisco extends City {}

```
 We’ll use these classes to write a method that has each kind of variance.

 
>  **Note:** The `*variantOf` types below are not a part of Flow, they are being used to explain variance.
> 
>  

 ### Invariance

 
```
function method(value: InvariantOf<City>) {...}

method(new Noun());         // error...
method(new City());         // okay
method(new SanFrancisco()); // error...

```
 * Invariance *does not* accept **supertypes**.
* Invariance *does not* accept **subtypes**.

 ### Covariance

 
```
function method(value: CovariantOf<City>) {...}

method(new Noun());         // error...
method(new City());         // okay
method(new SanFrancisco()); // okay

```
 * Covariance *does not* accept **supertypes**.
* Covariance *does* accept **subtypes**.

 ### Contravariance

 
```
function method(value: ContravariantOf<City>) {...}

method(new Noun());         // okay
method(new City());         // okay
method(new SanFrancisco()); // error...

```
 * Contravariance *does* accept **supertypes**.
* Contravariance *does not* accept **subtypes**.

 ### Bivariance

 
```
function method(value: BivariantOf<City>) {...}
method(new Noun());         // okay
method(new City());         // okay
method(new SanFrancisco()); // okay

```
 * Bivariance *does* accept **supertypes**.
* Bivariance *does* accept **subtypes**.

 As a result of having weak dynamic typing, JavaScript doesn’t have any of these, you can use any type at any time.

 Variance in Classes
-------------------

 To get a sense of when and why the different kinds of variance matters, let’s talk about methods of subclasses and how they get type checked.

 We’ll quickly set up our `BaseClass` which will define just one method that accepts an input value with the type `City` and a returned output also with the type `City`.

 
```
class BaseClass {
  method(value: City): City { ... }
}

```
 Now, let’s walk through different definitions of `method()` in a couple different *subclasses*.

 ### Equally specific inputs and outputs — Good

 To start, we can define a SubClass that extends our BaseClass. Here you can see that the value and the return type are both City just like in BaseClass:

 
```
class SubClass extends BaseClass {
  method(value: City): City { ... }
}

```
 This is okay because if something else in your program is using `SubClass` as if it were a `BaseClass`, it would still be using a `City` and wouldn’t cause any issues.

 ### More specific outputs — Good

 Next, we’ll have a different `SubClass` that returns a more specific type:

 
```
class SubClass extends BaseClass {
  method(value: City): SanFrancisco { ... }
}

```
 This is also okay because if something is using `SubClass` as if it were a `BaseClass` they would still have access to the same interface as before because `SanFrancisco` is just a `City` with a little more information.

 ### Less specific outputs — Bad

 Next, we’ll have a different `SubClass` that returns a less specific type:

 
```
class SubClass extends BaseClass {
  method(value: City): Noun { ... } // ERROR!!
}

```
 In Flow this will cause an error because if you are expecting to get a return value of a `City`, you may be using something that doesn’t exist on `Noun`, which could easily cause an error at runtime.

 ### Less specific inputs — Good

 Next, we’ll have another SubClass that accepts a value of a less specific type.

 
```
class SubClass extends BaseClass {
  method(value: Noun): City { ... }
}

```
 This is perfectly fine because if we pass in a more specific type we’ll still have all the information we need to be compatible with `Noun`.

 ### More specific inputs — Bad

 Finally, we’ll have yet another `SubClass` that accepts a value of a more specific type.

 
```
class SubClass extends BaseClass {
  method(value: SanFrancisco): City { ... } // ERROR!!
}

```
 This is an error in Flow because if you are expecting a `SanFrancisco` and you get a `City` you could be using something that only exists on `SanFrancisco` which would cause an error at runtime.

 All of this is why Flow has contravariant inputs (accepts less specific types to be passed in), and covariant outputs (allows more specific types to be returned).



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/lang/variance>

Width Subtyping
===============

 It’s safe to use an object with “extra” properties in a position that is annotated with a specific set of properties.

 
```
// @flow
function method(obj: { foo: string }) {
  // ...
}

method({
  foo: "test", // Works!
  bar: 42      // Works!
});

```
 Within `method`, we know that `obj` has at least a property `foo` and the property access expression `obj.foo` will have type `string`.

 This is a kind of subtyping commonly referred to as “width subtyping” because a type that is “wider” (i.e., has more properties) is a subtype of a narrower type.

 So in the following example, `obj2` is a *subtype* of `obj1`.

 
```
let obj1 = { foo: 'test' };
let obj2 = { foo: 'test', bar: 42 };

```
 However, it’s often useful to know that a property is definitely absent.

 
```
// @flow
function method(obj: { foo: string } | { bar: number }) {
  if (obj.foo) {
    (obj.foo: string); // Error!
  }
}

```
 The above code has a type error because Flow would also allow the call expression `method({ foo: 1, bar: 2 })`, because `{ foo: number, bar: number }` is a subtype of `{ bar: number }`, one of the members of the parameter’s union type.

 For cases like this where it’s useful to assert the absence of a property, Flow provides a special syntax for [“exact” object types](https://flow.org/en/types/objects/#toc-exact-object-types).

 
```
// @flow
function method(obj: {| foo: string |} | {| bar: number |}) {
  if (obj.foo) {
    (obj.foo: string); // Works!
  }
}

```
 [Exact object types](https://flow.org/en/types/objects/#toc-exact-object-types) disable width subtyping, and do not allow additional properties to exist.

 Using exact object types lets Flow know that no extra properties will exist at runtime, which allows [refinements](../refinements) to get more specific.

 
```
// @flow
function method(obj: {| foo: string |} | {| bar: number |}) {
  if (obj.foo) {
    (obj.foo: string); // Works!
  }
}

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/lang/width-subtyping>

Defining enums
==============

 Learn how to define a Flow Enum. Looking for a quick overview? Check out the [Quickstart Guide](../index#toc-quickstart).

 An enum declaration is a statement. Its name defines both a value (from which to [access its members](../using-enums#toc-accessing-enum-members), and call its [methods](../using-enums#toc-methods)), and a type (which can be [used as an annotation](../using-enums#toc-using-as-a-type-annotation) for the type of its members).

 Enum members must all be of the same type, and those members can be one of four types: [string](#toc-string-enums), [number](#toc-number-enums), [boolean](#toc-boolean-enums), and [symbol](#toc-symbol-enums).

 Every enum has some common properties:

 ### Consistent member type

 The type of the enum members must be consistent. For example, you can’t mix `string` and `number` members in one enum. They must all be strings, numbers, or booleans (you do not provide values for `symbol` based enums).

 ### Member name starting character

 Member names must be valid identifiers (e.g. not start with numbers), and must not start with lowercase `a` through `z`. Names starting with those letters are reserved for enum [methods](../using-enums#toc-methods) (e.g. `Status.cast(...)`).

 This is not allowed:

 
```
// @flow
enum Status {
  active, // Error: names can't start with lowercase 'a' through 'z'
}

```
 ### Unique member names

 Member names must be unique. This is not allowed:

 
```
// @flow
enum Status {
  Active,
  Active, // Error: the name 'Active` was already used above
}

```
 ### Literal member values

 If you specify a value for an enum member, it must be a literal (string, number, or boolean), not a computed value. This is not allowed:

 
```
// @flow
enum Status {
  Active = 1 + 2, // Error: the value must be a literal
}

```
 ### Unique member values

 Member values must be unique. This is not allowed:

 
```
enum Status {
  Active = 1,
  Paused = 1, // Error: the value has already been used above
}

```
 ### Fixed at declaration

 An enum is not extendable, so you can’t add new members after the fact while your code is running. At runtime, enum member values can’t change and the members can’t be deleted. In this way they act like a frozen object.

 String enums
------------

 String enums are the default. If you don’t specify an `of` clause (e.g. `enum Status of number {}`, `enum Status of symbol {}`, etc.), and do not specify any values (e.g. `enum Status {Active = 1}`) then the definition will default to be a string enum.

 Unlike the other types of enums (e.g. number enums), you can either specify values for the enum members, or not specify values and allow them to be defaulted.

 If you don’t specify values for your enum members, they default to strings which are the same as the name of your members.

 
```
enum Status {
  Active,
  Paused,
  Off,
}

```
 Is the same as:

 
```
enum Status {
  Active = 'Active',
  Paused = 'Paused',
  Off = 'Off',
}

```
 You must consistently either specify the value for all members, or none of the members. This is not allowed:

 
```
// @flow
enum Status {
  Active = 'active',
  Paused = 'paused',
  Off, // Error: you must specify a value for all members (or none of the members)
}

```
 Optionally, you can use an `of` clause:

 
```
enum Status of string {
  Active,
  Paused,
  Off,
}

```
 We infer the type of the enum based on its values if there is no `of` clause. Using an `of` clause will ensure that if you use incorrect values, the error message will always interpret it as an enum of that type.

 Number enums
------------

 Number enums must have their values specified.

 You can specify a number enum like this:

 
```
enum Status {
  Active = 1,
  Paused = 2,
  Off = 3,
}

```
 Optionally, you can use an `of` clause:

 
```
enum Status of number {
  Active = 1,
  Paused = 2,
  Off = 3,
}

```
 We do not allow defaulting of number enums (unlike some other languages), because if a member from the middle of such an enum is added or removed, all subsequent member values would be changed. This can be unsafe (e.g. push safety, serialization, logging). Requiring the user to be explicit about the renumbering makes them think about the consequences of doing so.

 The value provided must be a number literal. (Note: there is no literal for negative numbers in JavaScript, they are the application of a unary `-` operation on a number literal.) We could expand allowed values in the future to include certain non-literals, if requests to do so arise.

 Boolean enums
-------------

 Boolean enums must have their values specified. Boolean enums can only have two members.

 You can specify a boolean enum like this:

 
```
enum Status {
  Active = true,
  Off = false,
}

```
 Optionally, you can use an `of` clause:

 
```
enum Status of boolean {
  Active = true,
  Off = false,
}

```
 Symbol enums
------------

 Symbol enums can’t have their values specified. Each member is a new symbol, with the symbol description set to the name of the member. You must use the `of` clause with symbol enums, to distinguish them from string enums, which are the default when omitting values.

 You can specify a symbol enum like this:

 
```
enum Status of symbol {
  Active,
  Paused,
  Off,
}

```
 Flow Enums with Unknown Members
-------------------------------

 You can specify that your enum contains “unknown members” by adding a `...` to the end of the declaration:

 
```
enum Status {
  Active,
  Paused,
  Off,
  ...
}

```
 When this is used, Flow will always require a `default` when [switching over the enum](../using-enums#toc-exhaustive-checking-with-unknown-members), even if all known enum members are checked. The `default` checks for “unknown” members you haven’t explicitly listed.

 This feature is useful when an enum value crosses some boundary and the enum declaration on each side may have different memebers. For example, an enum definition which is used on both the client and the server: an enum member could be added, which would be immediately seen by the server, but could be sent to an outdated client which isn’t yet aware of the new member.

 One use case for this would be the JS output of [GraphQL Enums](https://graphql.org/learn/schema/#enumeration-types): Flow Enums with unknown members could be used instead of the added `'%future added value'` member.

 Enums at runtime
----------------

 Enums exist as values at runtime. We use a [Babel transform](https://www.npmjs.com/package/babel-plugin-transform-flow-enums) to transform Flow Enum declarations into calls to the [enums runtime](https://www.npmjs.com/package/flow-enums-runtime) (read more in the [enabling enums documentation](../enabling-enums)). We use a runtime so all enums can share an implementation of the enum [methods](../using-enums#toc-methods).

 We use `Object.create(null)` for enums’ prototype (which has the enum methods), so properties in `Object.prototype` will not pollute enums. The only own properties of the enum object are the enum members. The members are non-enumerable (use the [`.members()` method](../using-enums#toc-members) for that). The entire enum object is frozen, so it cannot be modified.

 Style guide
-----------

 ### Naming enums

 We encourage you to define enum names in `PascalCase`, following the naming conventions of other types. All caps names (e.g. `STATUS`) are harder to read and discouraged.

 We encourage you to name enums in the singular. E.g. `Status`, not `Statuses`. Just like the type of `true` and `false` is `boolean`, not `booleans`.

 Don’t append `Enum` to the name (e.g. don’t name your enum `StatusEnum`). This is unnecessary, just like we don’t append `Class` to every class name, and `Type` to every type alias.

 ### Naming enum members

 We encourage you to define enum member names in `PascalCase`. All caps names (e.g. `ACTIVE`) are harder to read and discouraged. Additionally, since Flow enforces that these are constants, you don’t need to use the name to signal that intent to the programmer.

 See also: the rule about [enum member name starting characters](#toc-member-name-starting-character).

 ### Don’t create a separate type

 A Flow Enum, like a class, is both a type and a value. You don’t need to create a separate type alias, you can use the enum name.

 ### Use dot access for accessing members

 Prefer `Status.Active` vs. `const {Active} = Status; Active`. This makes it easier find uses of the enum with text search, and makes it clearer to the reader what enum is involved. Additionally, this is required for [switch statements involving enums](../using-enums#toc-exhaustively-checking-enums-with-a-switch).



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/enums/defining-enums>

Flow Annotate-Exports
=====================

 Upgrading to [Types-First](https://flow.org/en/lang/types-first) mode may require a substantial number of type annotations at module boundaries. To help with the process of upgrading large codebases, we are providing a codemod command, whose goal is to fill in these missing annotations. This command is included in the Flow binary in versions `>= 0.125`.

 
>  Note: As of version 0.134, types-first is the default mode. If you are using a version `>=0.134`, make sure you set `types_first=false` in your .flowconfig while running this codemod.
> 
>  

 This command uses types that Flow infers, to fill in positions that would otherwise raise *signature-verification* failures. It will include the necessary type import statements, as long as the respective types are exported from their defining modules.

 It is designed for use on multiple files at once, rather than one file at a time. For this reason it doesn’t connect to an existing Flow server, but rather starts a checking process of its own.

 As is typical with such mechanized approaches, it comes with a few caveats:

 1. It won’t be able to fill in every required type annotation. Some cases will require manual effort.
2. Inserted annotations may cause new flow errors, since it’s not always possible to match inferred type with types that can be written as annotations.
3. File formatting may be affected. If a code formatter (e.g. prettier) is used, it is recommended that you run it after the codemod has finished running.

 How to apply the codemod
------------------------

 A typical way to invoke this command is

 
```
flow codemod annotate-exports \
  --write \
  --repeat \
  --log-level info \
  /path/to/folder \
  2> out.log
```
 This command will transform files under `/path/to/folder`. This does not need to be the root directory (the one containing `.flowconfig`).

 It uses the following flags:

 * `--write` will update files that require annotations under `/path/to/folder` in-place. Without this flag the resulting files will be printed on the command line.
* `--repeat` ensures that the transformation will be applied until no more files change. This mode is necessary here, because each new type the codemod adds may require new locations to be annotated.
* `--log-level info` outputs useful debugging information in the standard error stream. This option might lead to verbose output, so we’re redirecting the error output to a log file `out.log`.

 Another convenient way to provide the input is by passing the flag

 
```
--input-file file.txt
```
 where `file.txt` contains a specific list of files to be transformed.

 Codemod output
--------------

 After each iteration of the codemod, a summary will be printed on the CLI. This summary includes statistical information about the number of annotations that were added, and how many locations were skipped. It also prints counts for various kinds of errors that were encountered. These can be matched to the errors printed in the logs.

 A common error case is when a type `A`, defined in a file `a.js`, but not exported, is inferred in file `b.js`. The codemod will skip adding this annotation and report an error in the logs. The fix this case, you can export `A` in `a.js`. Note that it is not necessary to manually import `A` in `b.js`. The codemod will do this automatically.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/cli/annotate-exports>

Event Handling
==============

 In the [React docs “Handling Events” section](https://facebook.github.io/react/docs/handling-events.html) a few different recommendations are provided on how to define event handlers. If you are using Flow we recommend that you use [property initializer syntax](https://babeljs.io/docs/plugins/transform-class-properties/) as it is the easiest to statically type. Property initializer syntax looks like this:

 
```
class MyComponent extends React.Component<{}> {
  handleClick = event => { /* ... */ };
}

```
 To type event handlers you may use the `SyntheticEvent<T>` types like this:

 
```
import * as React from 'react';

class MyComponent extends React.Component<{}, { count: number }> {
  handleClick = (event: SyntheticEvent<HTMLButtonElement>) => {
    // To access your button instance use `event.currentTarget`.
    (event.currentTarget: HTMLButtonElement);

    this.setState(prevState => ({
      count: prevState.count + 1,
    }));
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.handleClick}>
          Increment
        </button>
      </div>
    );
  }
}

```
 There are also more specific synthetic event types like `SyntheticKeyboardEvent<T>`, `SyntheticMouseEvent<T>`, or `SyntheticTouchEvent<T>`. The `SyntheticEvent<T>` types all take a single type argument. The type of the HTML element the event handler was placed on.

 If you don’t want to add the type of your element instance you can also use `SyntheticEvent` with *no* type arguments like so: `SyntheticEvent<>`.

 
>  **Note:** To get the element instance, like `HTMLButtonElement` in the example above, it is a common mistake to use `event.target` instead of `event.currentTarget`. The reason why you want to use `event.currentTarget` is that `event.target` may be the wrong element due to [event propagation](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Examples#Example_5:_Event_Propagation).
> 
>  

 
>  **Note:** React uses its own event system so it is important to use the `SyntheticEvent` types instead of the DOM types such as `Event`, `KeyboardEvent`, and `MouseEvent`.
> 
>  

 The `SyntheticEvent<T>` types that React provides and the DOM events they are related to are:

 * `SyntheticEvent<T>` for [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event)
* `SyntheticAnimationEvent<T>` for [AnimationEvent](https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent)
* `SyntheticCompositionEvent<T>` for [CompositionEvent](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent)
* `SyntheticInputEvent<T>` for [InputEvent](https://developer.mozilla.org/en-US/docs/Web/API/InputEvent)
* `SyntheticUIEvent<T>` for [UIEvent](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent)
* `SyntheticFocusEvent<T>` for [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent)
* `SyntheticKeyboardEvent<T>` for [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent)
* `SyntheticMouseEvent<T>` for [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent)
* `SyntheticDragEvent<T>` for [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent)
* `SyntheticWheelEvent<T>` for [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent)
* `SyntheticTouchEvent<T>` for [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent)
* `SyntheticTransitionEvent<T>` for [TransitionEvent](https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent)



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/react/events>

Flow Coverage
=============

 The coverage command provides a metric of the amount of checking that Flow has performed on each part of your code. A program with high Flow coverage should increase your confidence that Flow has detected any potential runtime errors.

 The determining factor for this is the presence of [`any`](../types/any) in the inferred type of each expression. An expression whose inferred type is `any` is considered *uncovered*, otherwise it is considered *covered*.

 To see why this metric was chosen for determining Flow’s effectiveness, consider the example

 
```
const one: any = 1;
one();

```
 This code leads to a runtime type error, since we are attempting to perform a call on a number. Flow, however, does not flag an error here, because we have annotated variable `one` as `any`. Flow’s checking is effectively turned off whenever `any` is involved, so it will silently allow the call. The use of this *unsafe* type has rendered the type checker ineffective, and the coverage metric is here to surface this, by reporting all instances of `one` as uncovered.

 Design Space
------------

 **Which types should be “covered”?**

 What was described above is a rather coarse grained way to determine coverage. One could imagine a criterion that flags expressions as uncovered if *any* part of their type includes `any`, for example `Array<any>`. While there is value in a metric like this, the “uncovered” part of the type will typically be uncovered through various operations on values of this type. For example, in the code

 
```
declare var arr: Array<any>;
arr.forEach(x => {});

```
 the parameter `x` will be flagged as uncovered. Also, in practice, a strict criterion like this would be too noisy and rather expensive to compute on the fly.

 **Union types**

 An exception to this principle are union types: the type `number | any` is considered *uncovered*, even though technically `any` is not the top-level constructor. Unions merely encode an option among *a set of* other types. In that sense we are conservatively viewing an expression as uncovered, when at least one possible type of that expression causes limited checking. For example, in the code

 
```
let x: number | any = 1;
x = "a";

```
 Flow will let you assign anything to `x`, which reduces confidence in the use of `x` as a number. Thus `x` is considered uncovered.

 **The empty type**

 An interesting type from a coverage perspective is the `empty` type. This type roughly corresponds to *dead code*. As such checking around expressions with type `empty` is more relaxed, but for a good reason: this code will not be executed at runtime. Since it is a common practice to clean up such code, Flow coverage will also report code whose type is inferred to be `empty`, but distinguishes it from the case of `any`.

 Command Line Use
----------------

 To find out the coverage of a file foo.js with the following contents

 
```
// @flow
function add(one: any, two: any): number {
  return one + two;
}

add(1, 2);

```
 you can issue the following command

 
```
$ flow coverage file.js
Covered: 50.00% (5 of 10 expressions)
```
 This output means that 5 out of the 10 nodes of this program were inferred to have type `any`. To see exactly which parts are uncovered you can also pass one of the following flags:

 * `--color`: This will print foo.js on the terminal with the uncovered locations in red color.
* `--json`: This will list out all location spans that are uncovered under the tag `"uncovered_locs"`.

 Finally, as an example of dead code, consider the code

 
```
function untypedAdd(one, two) {
  return one + two;
}

```
 Note that function `untypedAdd` is never called, so `one` and `two` will be inferred to have type `empty`. In the colored version of this command these parts appear in blue color, and in the JSON version they are under the tag `"empty_locs"`.

 **Use on multiple files**

 If you want to check coverage of multiple files at once, Flow offers the `batch-coverage` command:

 
```
$ flow batch-coverage dir/
```
 will report coverage statistics for each file under `dir/`, as well as aggregate results.

 Note that `batch-coverage` requires a non-lazy Flow server.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/cli/coverage>

Creating Library Definitions
============================

 Before spending the time to write your own libdef, we recommend that you look to see if there is already a libdef for the third-party code that you’re addressing. `flow-typed` is a [tool and repository](https://github.com/flowtype/flow-typed/) for sharing common libdefs within the Flow community – so it’s a good way to knock out a good chunk of any public libdefs you might need for your project.

 However sometimes there isn’t a pre-existing libdef or you have third-party code that isn’t public and/or you really just need to write a libdef yourself. To do this you’ll start by creating a `.js` file for each libdef you’re going to write and put them in the `/flow-typed` directory at the root of your project. In these libdef file(s) you’ll use a special set of Flow syntax (explained below) to describe the interfaces of the relevant third-party code.

 Declaring A Global Function
---------------------------

 To declare a global function that should be accessible throughout your project, use the `declare function` syntax in a libdef file:

 **flow-typed/myLibDef.js**

 
```
declare function foo(a: number): string;

```
 This tells Flow that any code within the project can reference the `foo` global function, and that the function takes one argument (a `number`) and it returns a `string`.

 Declaring A Global Class
------------------------

 To declare a global class that should be accessible throughout your project, use the `declare class` syntax in a libdef file:

 **flow-typed/myLibDef.js**

 
```
declare class URL {
  constructor(urlStr: string): URL;
  toString(): string;

  static compare(url1: URL, url2: URL): boolean;
}

```
 This tells Flow that any code within the project can reference the `URL` global class. Note that this class definition does not have any implementation details – it exclusively defines the interface of the class.

 Declaring A Global Variable
---------------------------

 To declare a global variable that should be accessible throughout your project, use the `declare var` syntax in a libdef file:

 **flow-typed/myLibDef.js**

 
```
declare var PI: number;

```
 This tells Flow that any code within the project can reference the `PI` global variable – which, in this case, is a `number`.

 Declaring A Global Type
-----------------------

 To declare a global type that should be accessible throughout your project, use the `declare type` syntax in a libdef file:

 **flow-typed/myLibDef.js**

 
```
declare type UserID = number;

```
 This tells Flow that any code within the project can reference the `UserID` global type – which, in this case, is just an alias for `number`.

 Declaring A Module
------------------

 Often, third-party code is organized in terms of modules rather than globals. To write a libdef that declares the presence of a module you’ll want to use the `declare module` syntax:

 
```
declare module "some-third-party-library" {
  // This is where we'll list the module's exported interface(s)
}

```
 The name specified in quotes after `declare module` can be any string, but it should correspond to the same string you’d use to `require` or `import` the third-party module into your project. For defining modules that are accessed via a relative `require`/`import` path, please see the docs on the [`.flow` files](https://flow.org/en/declarations)

 Within the body of a `declare module` block, you can specify the set of exports for that module. However, before we start talking about exports we have to talk about the two kinds of modules that Flow supports: CommonJS and ES modules.

 Flow can handle both CommonJS and ES modules, but there are some relevant differences between the two that need to be considered when using `declare module`.

 ### Declaring An ES Module

 [ES modules](http://exploringjs.com/es6/ch_modules.html) have two kinds of exports: A **named** export and a **default** export. Flow supports the ability to declare either or both of these kinds of exports within a `declare module` body as follows:

 ###### Named Exports

 **flow-typed/some-es-module.js**

 
```
declare module "some-es-module" {
  // Declares a named "concatPath" export
  declare export function concatPath(dirA: string, dirB: string): string;
}

```
 Note that you can also declare other things inside the body of the `declare module`, and those things will be scoped to the body of the `declare module` – **but they will not be exported from the module**:

 **flow-typed/some-es-module.js**

 
```
declare module "some-es-module" {
  // Defines the type of a Path class within this `declare module` body, but
  // does not export it. It can only be referenced by other things inside the
  // body of this `declare module`
  declare class Path {
    toString(): string;
  }

  // Declares a named "concatPath" export which returns an instance of the
  // `Path` class (defined above)
  declare export function concatPath(dirA: string, dirB: string): Path;
}

```
 ###### Default Exports

 **flow-typed/some-es-module.js**

 
```
declare module "some-es-module" {
  declare class URL {
    constructor(urlStr: string): URL;
    toString(): string;

    static compare(url1: URL, url2: URL): boolean;
  }

  // Declares a default export whose type is `typeof URL`
  declare export default typeof URL;
}

```
 It is also possible to declare both **named** and **default** exports in the same `declare module` body.

 ### Declaring A CommonJS Module

 CommonJS modules have a single value that is exported (the `module.exports` value). To describe the type of this single value within a `declare module` body, you’ll use the `declare module.exports` syntax:

 **flow-typed/some-commonjs-module.js**

 
```
declare module "some-commonjs-module" {
  // The export of this module is an object with a "concatPath" method
  declare module.exports: {
    concatPath(dirA: string, dirB: string): string;
  };
}

```
 Note that you can also declare other things inside the body of the `declare module`, and those things will be scoped to the body of the `declare module`, **but they will not be exported from the module**:

 **flow-typed/some-commonjs-module.js**

 
```
declare module "some-commonjs-module" {
  // Defines the type of a Path class within this `declare module` body, but
  // does not export it. It can only be referenced by other things inside the
  // body of this `declare module`
  declare class Path {
    toString(): string;
  }

  // The "concatPath" function now returns an instance of the `Path` class
  // (defined above).
  declare module.exports: {
    concatPath(dirA: string, dirB: string): Path
  };
}

```
 NOTE: Because a given module cannot be both an ES module and a CommonJS module, it is an error to mix `declare export [...]` with `declare module.exports: ...` in the same `declare module` body.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/libdefs/creation>

Migrating from legacy patterns
==============================

 Learn how to migrate to Flow Enums from legacy JavaScript enum patterns like `Object.freeze`.

 First, learn how to [update the enum definition site](#toc-updating-definitions), and next learn how to [update files that import and use the enum](#toc-updating-usage).

 Updating definitions
--------------------

 ### Object.freeze

 If you are using `Object.freeze`, you can migrate to an enum if the values of the object are:

 * All the same primitive type, and that type is `boolean`, `string`, `number`, or `symbol`.
* All literals.
* Contain no duplicate values.

 Replace

 
```
const Status = Object.freeze({
  Active: 1,
  Paused: 2,
  Off: 3,
});

export type StatusType = $Values<typeof Status>;

export default Status;

```
 with

 
```
export default enum Status {
  Active = 1,
  Paused = 2,
  Off = 3,
}

```
 * Check to ensure that the key names do not start with lowercase ‘a’-‘z’ (disallowed in enums). If they do, you’ll need to rename the member names.
* Remove any usage of `$Keys<...>` or `$Values<...>` on the enum type, these are no longer needed as a Flow Enum defines a type itself (its name).
* Delete any type exports based on the enum, as you just need to export the Flow Enum. A Flow Enum acts as both a type and a value (like a class).

 Then, take a look at [how to update files that import and use the enum](#toc-updating-usage).

 ### keyMirror

 The `keyMirror` utility creates an object whose values are mirrors of its key names. You can replace `keyMirror` usage with a string based enum.

 Replace

 
```
import keyMirror from 'keyMirror';

const Status = keyMirror({
  Active: null,
  Paused: null,
  Off: null,
});

export type StatusType = $Keys<typeof Status>;

export default Status;

```
 with

 
```
export default enum Status {
  Active,
  Paused,
  Off,
}

```
 * Check to ensure that the key names do not start with lowercase ‘a’-‘z’ (disallowed in enums). If they do, you’ll need to rename the member names.
* Remove any usage of `$Keys<...>` on the enum type, it’s no longer needed as a Flow Enum defines a type itself (its name).
* Delete any type exports based on the enum, you just need to export the Flow Enum. A Flow Enum acts as both a type and a value (like a class).

 Then, take a look at [how to update files that import and use the enum](#toc-updating-usage).

 Updating usage
--------------

 ### Fix type imports

 Previous patterns required you to export (and then import) a type separate from the enum itself. Flow Enums are both types and values (like a class), so you just need to export the Flow Enum itself. Since there is now one export, you only need one import. Read more about [exporting enums](../using-enums#toc-exporting-enums) and [importing enums](../using-enums#toc-importing-enums).

 If you previously had:

 
```
const Status = Object.freeze({
  Active: 1,
  Paused: 2,
  Off: 3,
});
export type StatusType = $Values<typeof Status>;
export default Status;

```
 And you’ve replaced it with:

 
```
export default enum Status {
  Active = 1,
  Paused = 2,
  Off = 3,
}

```
 Then you need to fix the imports as well:

 #### If both type and value were imported

 For a user of the enum, if you previously imported both the type and the value, you can delete the type import and update annotations used.

 Change

 
```
import type {StatusType} from 'status';

import Status from 'status';

const myStatus: StatusType = Status.Active;

```
 to

 
```
// Type import is deleted

import Status from 'status';

const myStatus: Status = Status.Active; // Changed type annotation to just `Status`

```
 #### If only the type was imported

 For a user of the enum, if you previously imported just the type, change the type import to a default import rather than a named import.

 Change

 
```
import type {StatusType} from 'status';

function isActive(status: StatusType) { ... }

```
 to

 
```
// Remove the braces `{` `}` and changed the name - this is a default import now
import type Status from 'status';

function isActive(status: Status) { ... } // Changed type annotation to just `Status`

```
 ### Mapping enums to other values

 Sometimes you want to map from an enum value to some other value. Previously, we sometimes used object literals for this. With Flow Enums, use a function with a `switch` instead. The switch is [exhaustively checked](../using-enums#toc-exhaustively-checking-enums-with-a-switch), so Flow will ensure you update your mapping when you add or remove Flow Enum members.

 Replace this pattern

 
```
const STATUS_ICON: {[Status]: string} = {
  [Status.Active]: 'green-checkmark',
  [Status.Paused]: 'grey-pause',
  [Status.Off]: 'red-x',
};
const icon = STATUS_ICON[status];

```
 with

 
```
function statusIcon(status: Status): string {
  switch (status) {
    case Status.Active:
      return 'green-checkmark';
    case Status.Paused:
      return 'grey-pause';
    case Status.Off:
      return 'red-x';
  }
}
const icon = statusIcon(status);

```
 Read more about [mapping enums to other values](../using-enums#toc-mapping-enums-to-other-values).

 ### Usage as the representation type (e.g. a string)

 You can’t use a Flow Enum directly as its representation type (e.g. a `string`). If you get Flow errors about using an enum as its representation type, first try to refactor your code so that it expects the enum type instead of the representation type (e.g. change annotations from `string` to `Status`). If you really want to use the enum as its representation type, you can add in explicit casts. See [casting to represetation type](../using-enums#toc-casting-to-representation-type).

 ### Casting to the enum type

 If before you cast from an enum’s representation type (e.g. `string`) to the enum type with something like this:

 
```
function castToStatus(input: number): StatusType | void {
  switch(input) {
    case 1: return Status.Active;
    case 2: return Status.Paused;
    case 3: return Status.Off;
    default: return undefined;
  }
}

castToStatus(x);

```
 You can now just use the [cast](../using-enums#toc-cast) method:

 
```
Status.cast(x);

```
 ### Update switch statements

 Flow Enums are exhaustively checked in `switch` statements. You might need to update your code when you are switching over an enum value. Read more at [exhaustively checking enums in switch statements](../using-enums#toc-exhaustively-checking-enums-with-a-switch).

 ### Operations over enum members

 If previously you used functionality like `Object.values`, `Object.keys`, or `for-in` loops to get and operate on the enum members, you can use the [members method](../using-enums#toc-members) instead.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/enums/migrating-legacy-patterns>

Context
=======

 Flow can typecheck your React components that use the [context API](https://reactjs.org/docs/context.html) introduced in React 16.3.

 
>  **Note:** Typing context values requires Flow 0.70 or later.
> 
>  

 Flow will infer types from the way you use a context’s `{ Provider, Consumer }` pair:

 
```
import React from "react";

const Theme = React.createContext();

<Theme.Provider value="light" />;

<Theme.Consumer>{value => value.toUpperCase()}</Theme.Consumer>; // Error! `value` is nullable.

<Theme.Consumer>
  {value =>
    value
      ? value.toUpperCase() // Valid: `value` is a string.
      : null
  }
</Theme.Consumer>;

```
 If your context has a default value, Flow will type your consumer component accordingly:

 
```
import React from "react";

const Theme = React.createContext("light");

<Theme.Consumer>{value => value.toUpperCase()}</Theme.Consumer>; // Valid: `value` is a non-nullable string.

```
 To explicitly specify the type of a context value, pass a type parameter to `createContext`:

 
```
import React from "react";

const Theme = React.createContext<"light" | "dark">("light");

<Theme.Provider value="blue" />; // Error! "blue" is not one of the allowed values.

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/react/context>

Using enums
===========

 * [Accessing enum members](#toc-accessing-enum-members)
* [Using as a type annotation](#toc-using-as-a-type-annotation)
* [Casting to representation type](#toc-casting-to-representation-type)
* [Methods](#toc-methods)
	+ [.cast](#toc-cast)
	+ [.isValid](#toc-isvalid)
	+ [.members](#toc-members)
	+ [.getName](#toc-getname)
* [Exhaustively checking enums with a `switch`](#toc-exhaustively-checking-enums-with-a-switch)
* [Exhaustive checking with unknown members](#toc-exhaustive-checking-with-unknown-members)
* [Mapping enums to other values](#toc-mapping-enums-to-other-values)
* [Enums in a union](#toc-enums-in-a-union)
* [Exporting enums](#toc-exporting-enums)
* [Importing enums](#toc-importing-enums)
* [Generic enums](#toc-generic-enums)
* [When to not use enums](#toc-when-to-not-use-enums)

 Flow Enums are not a syntax for [union types](https://flow.org/en/types/unions/). They are their own type, and each member of a Flow Enum has the same type. Large union types can cause performance issues, as Flow has to consider each member as a separate type. With Flow Enums, no matter how large your enum is, Flow will always exhibit good performance as it only has one type to keep track of.

 We use the following enum in the examples below:

 
```
enum Status {
  Active,
  Paused,
  Off,
}

```
 Accessing enum members
----------------------

 Access members with the dot syntax:

 
```
const status = Status.Active;

```
 You can’t use computed access:

 
```
const x = "Active";
Status[x]; // Error: computed access on enums is not allowed

```
 Using as a type annotation
--------------------------

 The enum declaration defines both a value (from which you can access the enum members and methods) and a type of the same name, which is the type of the enum members.

 
```
function calculateStatus(): Status {
  ...
}

const status: Status = calculateStatus();

```
 Casting to representation type
------------------------------

 Enums do not implicitly coerce to their representation type or vice-versa. If you want to convert from the enum type to the representation type, you can use an explicit cast `(x: string)`:

 
```
const s: string = Status.Active; // Error: 'Status' is not compatible with 'string'

const statusString: string = (Status.Active: string);

```
 To convert from a nullable enum type to nullable string, you can do:

 
```
const maybeStatus: ?Status = ....;

const maybeStatusString: ?string = maybeStatus && (maybeStatus: string);

```
 If you want to convert from the representation type (e.g. `string`) to an enum type (if valid), check out the [cast method](#toc-cast).

 Methods
-------

 Enum declarations also define some helpful methods.

 Below, `TEnum` is the type of the enum (e.g. `Status`), and `TRepresentationType` is the type of the representation type for that enum (e.g. `string`).

 ### .cast

 Type: `cast(input: ?TRepresentationType): TEnum | void`

 The `cast` method allows you to safely convert a primitive value, like a `string`, to the enum type (if it is a valid value of the enum), and `undefined` otherwise.

 
```
const data: string = getData();
const maybeStatus: Status | void = Status.cast(data);
if (maybeStatus != null) {
  const status: Status = maybeStatus;
  // do stuff with status
}

```
 Set a default value in one line with the `??` operator:

 
```
const status: Status = Status.cast(data) ?? Status.Off;

```
 The type of the argument of `cast` depends on the type of enum. If it is a [string enum](../defining-enums#toc-string-enums), the type of the argument will be `string`. If it is a [number enum](../defining-enums#toc-number-enums), the type of the argument will be `number`, and so on. If you wish to cast a `mixed` value, first use a `typeof` refinement:

 
```
const data: mixed = ...;
if (typeof data === 'string') {
  const maybeStatus: Status | void = Status.cast(data);
}

```
 `cast` uses `this` (representing the object of enum members), so if you want to pass the function itself as a value, you should use an arrow function. For example:

 
```
const strings: Array<string> = ...;
// WRONG: const statuses: Array<?Status> = strings.map(Status.cast);
const statuses: Array<?Status> = strings.map((input) => Status.cast(input)); // Correct

```
 Runtime cost: For [mirrored string enums](../defining-enums#toc-string-enums) (e.g `enum E {A, B}`), as the member names are the same as the values, the runtime cost is constant - equivalent to calling `.hasOwnProperty`. For other enums, a `Map` is created on the first call, and subsequent calls simply call `.has` on the cached map. Thus the cost is amoritzed constant.

 ### .isValid

 Type: `isValid(input: ?TRepresentationType): boolean`

 The `isValid` method is like `cast`, but simply returns a boolean: `true` if the input supplied is a valid enum value, and `false` if it is not.

 
```
const data: string = getData();
const isStatus: boolean = Status.isValid(data);

```
 `isValid` uses `this` (representing the object of enum members), so if you want to pass the function itself as a value, you should use an arrow function. For example:

 
```
const strings: Array<string> = ...;
// WRONG: const statusStrings = strings.filter(Status.isValid);
const statusStrings = strings.filter((input) => Status.isValid(input)); // Correct

```
 Runtime cost: The same as described under `.cast` above.

 ### .members

 Type: `members(): Iterator<TEnum>`

 The `members` method returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#iterators) (that is iterable) of all the enum members.

 
```
const buttons = [];
function getButtonForStatus(status: Status) { ...  }

for (const status of Status.members()) {
  buttons.push(getButtonForStatus(status));
}

```
 The iteration order is guaranteed to be the same as the order of the members in the declaration.

 The enum is not enumerable or iterable itself (e.g. a for-in/for-of loop over the enum will not iterate over its members), you have to use the `.members()` method for that purpose.

 You can convert the iterable into an `Array` using: `Array.from(Status.members())`. You can make use of [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)’s second argument to map over the values at the same time you construct the array: e.g. `const buttonArray = Array.from(Status.members(), status => getButtonForStatus(status));`.

 ### .getName

 Type: `getName(value: TEnum): string`

 The `getName` method maps enum values to the string name of that value’s enum member. When using `number`/`boolean`/`symbol` enums, this can be useful for debugging and for generating internal CRUD UIs. For example:

 
```
enum Status {
  Active = 1,
  Paused = 2,
  Off = 3,
}
const status: Status = ...;

console.log(Status.getName(status));
// Will print a string, either "Active", "Paused", or "Off" depending on the value.

```
 Runtime cost: The same as described under `.cast` above. A single cached reverse map from enum value to enum name is used for `.cast`, `.isValid`, and `.getName`. The first call of any of those methods will create this cached map.

 Exhaustively checking enums with a `switch`
-------------------------------------------

 When checking an enum value in a `switch` statement, we enforce that you check against all possible enum members, and don’t include redundant cases. This helps ensure you consider all possibilities when writing code that uses enums. It especially helps with refactoring when adding or removing members, by pointing out the different places you need to update.

 
```
const status: Status = ...;

switch (status) { // Good, all members checked
  case Status.Active:
    break;
  case Status.Paused:
    break;
  case Status.Off:
    break;
}

```
 You can use `default` to match all members not checked so far:

 
```
switch (status) {
  case Status.Active:
    break;
  default: // When `Status.Paused` or `Status.Off`
    break;
}

```
 You can check multiple enum members in one switch case:

 
```
switch (status) {
  case Status.Active:
  case Status.Paused:
    break;
  case Status.Off:
    break;
}

```
 You must match against all of the members of the enum (or supply a `default` case):

 
```
// Error: you haven't checked 'Status.Off' in the switch
switch (status) {
  case Status.Active:
    break;
  case Status.Paused:
    break;
}

```
 You can’t repeat cases (as this would be dead code!):

 
```
switch (status) {
  case Status.Active:
    break;
  case Status.Paused:
    break;
  case Status.Off:
    break;
  case Status.Paused: // Error: you already checked for 'Status.Paused'
    break;
}

```
 A `default` case is redundant if you’ve already matched all cases:

 
```
switch (status) {
  case Status.Active:
    break;
  case Status.Paused:
    break;
  case Status.Off:
    break;
  default: // Error: you've already checked all cases, the 'default' is redundant
    break;
}
// The following is OK because the `default` covers the `Status.Off` case:
switch (status) {
  case Status.Active:
    break;
  case Status.Paused:
    break;
  default:
    break;
}

```
 Except if you are switching over an enum with [unknown members](../defining-enums#toc-flow-enums-with-unknown-members).

 If you nest exhaustively checked switches inside exhaustively checked switches, and are returning from each branch, you must add a `break;` after the nested switch:

 
```
switch (status) {
  case Status.Active:
    return 1;
  case Status.Paused:
    return 2;
  case Status.Off:
    switch (otherStatus) {
      case Status.Active:
        return 1;
      case Status.Paused:
        return 2;
      case Status.Off:
        return 3;
    }
    break;
}

```
 Remember, you can add blocks to your switch cases. They are useful if you want to use local variables:

 
```
switch (status) {
  case Status.Active: {
    const x = f();
    ...
    break;
  }
  case Status.Paused: {
    const x = g();
    ...
    break;
  }
  case Status.Off: {
    const y = ...;
    ...
    break;
  }
}

```
 If you didn’t add blocks in this example, the two declarations of `const x` would conflict and result in an error.

 Enums are not checked exhaustively in `if` statements or other contexts other than `switch` statements.

 Exhaustive checking with unknown members
----------------------------------------

 If your enum has [unknown members](../defining-enums#toc-flow-enums-with-unknown-members) (specified with the `...`), e.g.

 
```
enum Status {
  Active,
  Paused,
  Off,
  ...
}

```
 Then a `default` is always required when switching over the enum. The `default` checks for “unknown” members you haven’t explicitly listed.

 
```
switch (status) {
  case Status.Active:
    break;
  case Status.Paused:
    break;
  case Status.Off:
    break;
  default:
    // Checks for members not explicitly listed
}

```
 You can use the `require-explicit-enum-switch-cases` [Flow Lint](https://flow.org/en/linting/flowlint-comments/) to require that all known members are explicitly listed as cases. For example:

 
```
// flowlint-next-line require-explicit-enum-switch-cases:error
switch (status) {
  case Status.Active:
    break;
  case Status.Paused:
    break;
  default:
    break;
}

```
 Will trigger an error (without the lint there would be no error):

 
```
Incomplete exhaustive check: the member `Off` of enum `Status` has not been
considered in check of `status`. The default case does not check for the missing
members as the `require-explicit-enum-switch-cases` lint has been enabled.

```
 You can fix if by doing:

 
```
// flowlint-next-line require-explicit-enum-switch-cases:error
switch (status) {
  case Status.Active:
    break;
  case Status.Paused:
    break;
  case Status.Off: // Added the missing `Status.Off` case
    break;
  default:
    break;
}

```
 The `require-explicit-enum-switch-cases` lint is not one to enable globally, but rather on a per-`switch` basis when you want the behavior. With normal enums, for each `switch` statement on it, you can either provide a `default` or not, and thus decide if you want to require each case explicitly listed or not. Similarly for Flow Enums with unknown members, you can also enable this lint on a per-switch basis.

 The lint works for switches of regular Flow Enum types as well. It in effect bans the usage of `default` in that `switch` statement, by requiring the explicit listing of all enum members as cases.

 Mapping enums to other values
-----------------------------

 There are a variety of reasons you may want to map an enum value to another value, e.g. a label, icon, element, and so on.

 With previous patterns, it was common to use object literals for this purpose, however with Flow Enums we prefer functions which contain a switch, which we can exhaustively check.

 Instead of:

 
```
const STATUS_ICON: {[Status]: string} = {
  [Status.Active]: 'green-checkmark',
  [Status.Paused]: 'grey-pause',
  [Status.Off]: 'red-x',
};
const icon = STATUS_ICON[status];

```
 Which doesn’t actually guarantee that we are mapping each `Status` to some value, use:

 
```
function getStatusIcon(status: Status): string {
  switch (status) {
    case Status.Active:
      return 'green-checkmark';
    case Status.Paused:
      return 'grey-pause';
    case Status.Off:
      return 'red-x';
  }
}
const icon = getStatusIcon(status);

```
 In the future if you add or remove an enum member, Flow will tell you to update the switch as well so it’s always accurate.

 If you actually want a dictionary which is not exhaustive, you can use a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map):

 
```
const counts = new Map<Status, number>([
  [Status.Active, 2],
  [Status.Off, 5],
]);
const activeCount: Status | void = counts.get(Status.Active);

```
 Flow Enums cannot be used as keys in object literals, as [explained later on this page](#toc-distinct-object-keys).

 Enums in a union
----------------

 If your enum value is in a union (e.g. `?Status`), first refine to only the enum type:

 
```
const status: ?Status = ...;

if (status != null) {
  (status: Status); // 'status' is refined to 'Status' at this point
  switch (status) {
    case Status.Active: break;
    case Status.Paused: break;
    case Status.Off: break;
  }
}

```
 If you want to refine *to* the enum value, you can use `typeof` with the representation type, for example:

 
```
const val: Status | number = ...;

// 'Status' is a string enum
if (typeof val === 'string') {
  (val: Status); // 'val' is refined to 'Status' at this point
  switch (val) {
    case Status.Active: break;
    case Status.Paused: break;
    case Status.Off: break;
  }
}

```
 Exporting enums
---------------

 An enum is a type and a value (like a class is). To export both the type and the value, export it like a you would a value:

 
```
export enum Status {}

```
 Or, as the default export (note: you must always specify an enum name, `export default enum {}` is not allowed):

 
```
export default enum Status {}

```
 Using CommonJS:

 
```
enum Status {}
module.exports = Status;

```
 To export **only** its type, but not the value, you can do:

 
```
enum Status_ {}
export type Status = Status_;

```
 Since `export type` introduces a new binding with that name, the enum and the exported type must have different names. Other functions within the file will still have access to the enum implementation.

 Importing enums
---------------

 If you have exported an enum like this:

 
```
// status.js
export default enum Status {
  Active,
  Paused,
  Off,
}

```
 You can import it as both a value and a type like this:

 
```
import Status from 'status';

const x: Status /* used as type */ = Status.Active /* used as value */;

```
 If you only need to use the type, you can import it as a type:

 
```
import type Status from 'status';

function printStatus(status: Status) {
  ...
}

```
 Using CommonJS:

 
```
const Status = require('status');

```
 Generic enums
-------------

 There is currently no way to specify a generic enum type, but there have been enough requests that it is something we will look into in the future.

 For some use cases of generic enums, you can currently ask users to supply functions which call the enum [methods](#toc-methods) instead (rather than passing in the enum itself), for example:

 
```
function castToEnumArray<TRepresentationType, TEnum>(
  f: TRepresentationType => TEnum,
  xs: Array<TRepresentationType>,
): Array<TEnum | void> {
  return xs.map(f);
}

castToEnumArray((input) => Status.cast(input), ["Active", "Paused", "Invalid"]);

```
 When to not use enums
---------------------

 Enums are designed to cover many use cases and exhibit certain benefits. The design makes a variety of trade-offs to make this happen, and in certain situations, these trade-offs might not be right for you. In these cases, you can continue to use existing patterns to satisfy your use cases.

 ### Distinct object keys

 You can’t use enum members as distinct object keys.

 The following pattern works because the types of `LegacyStatus.Active` and `LegacyStatus.Off` are different. One has the type `'Active'` and one has the type `'Off'`.

 
```
const LegacyStatus = Object.freeze({
  Active: 'Active',
  Paused: 'Paused',
  Off: 'Off',
});
const o = {
  [LegacyStatus.Active]: "hi",
  [LegacyStatus.Off]: 1,
};
const x: string = o[LegacyStatus.Active]; // OK
const y: number = o[LegacyStatus.Off]; // OK
const z: boolean = o[LegacyStatus.Active]; // Error - as expected

```
 We can’t use the same pattern with enums. All enum members have the same type, the enum type, so Flow can’t track the relationship between keys and values.

 If you wish to map from an enum value to another value, you should use a [function with an exhaustively-checked switch instead](#toc-mapping-enums-to-other-values).

 ### Disjoint object unions

 A defining feature of enums is that unlike unions, each enum member does not form its own separate type. Every member has the same type, the enum type. This allows enum usage to be analyzed by Flow in a consistently fast way, however it means that in certain situations which require separate types, we can’t use enums. Consider the following union, following the [disjoint object union](https://flow.org/en/types/unions/#toc-disjoint-unions) pattern:

 
```
type Action =
  | {type: 'Upload', data: string}
  | {type: 'Delete', id: number};

```
 Each object type in the union has a single common field (`type`) which is used to distinguish which object type we are dealing with.

 We can’t use enum types for this field, because for this mechanism to work, the type of that field must be different in each member of the union, but enum members all have the same type.

 In the future, we might add the ability for enums to encapsulate additional data besides a key and a primitive value - this would allow us to replace disjoint object unions.

 ### Guaranteed inlining

 Flow Enums are designed to allow for inlining (e.g. [member values must be literals](../defining-enums#toc-literal-member-values), [enums are frozen](../defining-enums#toc-fixed-at-declaration)), however the inlining itself needs to be part of the build system (whatever you use) rather than Flow itself.

 While enum member access (e.g. `Status.Active`) can be inlined (other than [symbol enums](../defining-enums#toc-symbol-enums) which cannot be inlined due to the nature of symbols), usage of its methods (e.g. `Status.cast(x)`) cannot be inlined.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/enums/using-enums>

Babel
=====

 Flow and [Babel](http://babeljs.io/) are designed to work great together. It takes just a few steps to set them up together.

 If you don’t have Babel setup already, you can do that by following [this guide](http://babeljs.io/docs/setup/).

 Once you have Babel setup, install `@babel/preset-flow` with either [Yarn](https://yarnpkg.com/) or [npm](https://www.npmjs.com/).

 
```
yarn add --dev @babel/preset-flow
# or
npm install --save-dev @babel/preset-flow
```
 Then add `flow` to your Babel presets config.

 
```
{
  "presets": ["@babel/preset-flow"]
}
```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/tools/babel>

flow-remove-types
=================

 [`flow-remove-types`](https://github.com/facebook/flow/tree/master/packages/flow-remove-types) is a small CLI tool for stripping Flow type annotations from files. It’s a lighter-weight alternative to Babel for projects that don’t need everything Babel provides.

 First install `flow-remove-types` with either [Yarn](https://yarnpkg.com/) or [npm](https://www.npmjs.com/).

 
```
yarn add --dev flow-remove-types
# or
npm install --save-dev flow-remove-types
```
 If you then put all your source files in a `src` directory you can compile them to another directory by running:

 
```
yarn run flow-remove-types src/ -d lib/
```
 You can add this to your `package.json` scripts easily.

 
```
{
  "name": "my-project",
  "main": "lib/index.js",
  "scripts": {
    "build": "flow-remove-types src/ -d lib/",
    "prepublish": "yarn run build"
  }
}
```
 
>  **Note:** You’ll probably want to add a `prepublish` script that runs this transform as well, so that it runs before you publish your code to the npm registry.
> 
>  



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/tools/flow-remove-types>

ref functions
=============

 React allows you to grab the instance of an element or component with [`ref` functions](https://facebook.github.io/react/docs/refs-and-the-dom.html). To use a ref function add a [maybe instance type](https://flow.org/en/types/maybe/) to your class and assign your instance to that property in your ref function.

 
```
import * as React from 'react';

class MyComponent extends React.Component<{}> {
  // The `?` here is important because you may not always have the instance.
  button: ?HTMLButtonElement;

  render() {
    return <button ref={button => (this.button = button)}>Toggle</button>;
  }
}

```
 The `?` in `?HTMLButtonElement` is important. In the example above the first argument to `ref` will be `HTMLButtonElement | null` as React will [call your `ref` callback with null](https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element) when the component unmounts. Also, the `button` property on `MyComponent` will not be set until React has finished rendering. Until then your `button` ref will be undefined. Protect yourself against these cases and use a `?` (like in `?HTMLButtonElement`) to protect yourself from bugs.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/react/refs>

ESLint
======

 ESLint is a static analysis tool which can help you quickly find and fix bugs and stylistic errors in your code. The rules ESLint provide complement the checks provided by Flow’s type system.

 You can quick-start setup ESLint, install `hermes-eslint` with either [Yarn](https://yarnpkg.com/) or [npm](https://www.npmjs.com/).

 
```
yarn add --dev eslint hermes-eslint eslint-plugin-ft-flow
# or
npm install --save-dev eslint hermes-eslint eslint-plugin-ft-flow
```
 Then create a `.eslintrc.js` file in your project root with the following:

 
```
module.exports = {
  root: true,
  parser: 'hermes-eslint',
  plugins: [
    'ft-flow'
  ],
  extends: [
    'eslint:recommended',
    'plugin:ft-flow/recommended',
  ],
};

```
 For more information about configuring ESLint, [check out the ESLint docs](https://eslint.org/).

 You can then lint your codebase with:

 
```
yarn run eslint . --ext .js,.jsx
# or
npm run eslint . --ext .js,.jsx
```
 Usage With Prettier
-------------------

 If you use [`prettier`](https://www.npmjs.com/package/prettier), there is also a helpful config to help ensure ESLint doesn’t report on formatting issues that prettier will fix: [`eslint-config-prettier`](https://www.npmjs.com/package/eslint-config-prettier).

 Using this config by adding it to the ***end*** of your `extends`:

 
```
module.exports = {
    root: true,
    parser: 'hermes-eslint',
    plugins: [
      'ft-flow'
    ],
    extends: [
      'eslint:recommended',
      'plugin:ft-flow/recommended',
+     'prettier',
    ],
  };
```
 Additional Plugins
------------------

 ESLint plugins provide additional rules and other functionality on top of ESLint. Below are just a few examples that might be useful:

 * Helpful language rules by the Flow team: [`eslint-plugin-fb-flow`](https://www.npmjs.com/package/eslint-plugin-fb-flow)
* React best practices: [`eslint-plugin-react`](https://www.npmjs.com/package/eslint-plugin-react) and [`eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks)
* Jest testing: [`eslint-plugin-jest`](https://www.npmjs.com/package/eslint-plugin-jest)
* Import/export conventions : [`eslint-plugin-import`](https://www.npmjs.com/package/eslint-plugin-import)
* NodeJS best practices: [`eslint-plugin-node`](https://www.npmjs.com/package/eslint-plugin-node)
* ESLint comment restrictions: [`eslint-plugin-eslint-comments`](https://www.npmjs.com/package/eslint-plugin-eslint-comments)

 Every plugin that is out there includes documentation on the various configurations and rules they offer. A typical plugin might be used like:

 
```
module.exports = {
    root: true,
    parser: 'hermes-eslint',
    plugins: [
      'ft-flow'
+     'jest',
    ],
    extends: [
      'eslint:recommended',
      'plugin:ft-flow/recommended',
+     'plugin:jest/recommended',
    ],
  };
```
 Search [“eslint-plugin” on npm](https://www.npmjs.com/search?q=eslint-plugin) for more.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/tools/eslint>

Create React App
================

 [Create React App](https://github.com/facebookincubator/create-react-app) already supports Flow by default. All you need to do is [install Flow](https://flow.org/en/install/) and create a `.flowconfig` file by running `flow init`.

 
```
create-react-app my-app && cd my-app
yarn add --dev flow-bin
yarn run flow init
```
 Flow will be run as part of create-react-app’s scripts.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/tools/create-react-app>

Redux
=====

 [Redux](http://redux.js.org) has three major parts that should be typed:

 * State
* Actions
* Reducers

 Typing Redux state
------------------

 Typing your [state](http://redux.js.org/docs/introduction/ThreePrinciples.html#single-source-of-truth) object, works the same as typing any other object in Flow.

 
```
type State = {
  users: Array<{
    id: string,
    name: string,
    age: number,
    phoneNumber: string,
  }>,
  activeUserID: string,
  // ...
};

```
 We can use this type alias to make sure reducers work correctly.

 ### Typing Redux state immutability

 Redux state [is meant to be immutable](http://redux.js.org/docs/introduction/ThreePrinciples.html#state-is-read-only): creating a new state object instead of changing properties on a single object.

 You can enforce this in Flow by making every property effectively “read-only” using “covariant” properties throughout your state object.

 
```
type State = {
  +users: Array<{
    +id: string,
    +name: string,
    +age: number,
    +phoneNumber: string,
  }>,
  +activeUserID: string,
  // ...
};

```
 Now Flow will complain when you try to write to any of these properties.

 
```
// @flow
type State = {
  +foo: string
};

let state: State = {
  foo: "foo"
};

state.foo = "bar"; // Error!

```
 Typing Redux actions
--------------------

 The base type for Redux [actions](http://redux.js.org/docs/basics/Actions.html) is an object with a `type` property.

 
```
type Action = {
  +type: string,
};

```
 But you’ll want to use more specific types for your actions using disjoint unions and each individual type of action.

 
```
type Action =
  | { type: "FOO", foo: number }
  | { type: "BAR", bar: boolean }
  | { type: "BAZ", baz: string };

```
 Using disjoint unions, Flow will be able to understand your reducers much better.

 ### Typing Redux action creators

 In order to type your Redux [action creators](http://redux.js.org/docs/basics/Actions.html#action-creators), you’ll want to split up your `Action` disjoint union into separate action types.

 
```
type FooAction = { type: "FOO", foo: number };
type BarAction = { type: "BAR", bar: boolean };

type Action =
  | FooAction
  | BarAction;

```
 Then to type the action creator, just add a return type of the appropriate action.

 
```
// @flow
type FooAction = { type: "FOO", foo: number };
type BarAction = { type: "BAR", bar: boolean };

type Action =
  | FooAction
  | BarAction;

function foo(value: number): FooAction {
  return { type: "FOO", foo: value };
}

function bar(value: boolean): BarAction {
  return { type: "BAR", bar: value };
}

```
 ### Typing Redux thunk actions

 In order to type your Redux [thunk actions](http://redux.js.org/docs/advanced/AsyncActions.html#async-action-creators), you’ll add types for `ThunkAction` as a function `Dispatch`, and `GetState`. `GetState` is a function that returns an `Object`. `Dispatch` accepts a disjoint union of `Action`, `ThunkAction`, `PromiseAction` and `Array<Action>` and can return `any`.

 
```
type Dispatch = (action: Action | ThunkAction | PromiseAction) => any;
type GetState = () => State;
type ThunkAction = (dispatch: Dispatch, getState: GetState) => any;
type PromiseAction = Promise<Action>;

```
 Then to type a thunk action creator, add a return type of a `ThunkAction` to your action creator.

 
```
type Action =
  | { type: "FOO", foo: number }
  | { type: "BAR", bar: boolean };

type GetState = () => State;
type PromiseAction = Promise<Action>;
type ThunkAction = (dispatch: Dispatch, getState: GetState) => any;
type Dispatch = (action: Action | ThunkAction | PromiseAction | Array<Action>) => any;


function foo(): ThunkAction {
  return (dispatch, getState) => {
    const baz = getState().baz
    dispatch({ type: "BAR", bar: true })
    doSomethingAsync(baz)
      .then(value => {
        dispatch({ type: "FOO", foo: value })
      })
    }
}

```
 Typing Redux reducers
---------------------

 [Reducers](http://redux.js.org/docs/basics/Reducers.html) take the state and actions that we’ve typed and pulls them together for one method.

 
```
function reducer(state: State, action: Action): State {
  // ...
}

```
 You can also validate that you have handled every single type of action by using the `empty` type in your `default` case.

 
```
// @flow
type State = { +value: boolean };

type FooAction = { type: "FOO", foo: boolean };
type BarAction = { type: "BAR", bar: boolean };

type Action = FooAction | BarAction;

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "FOO": return { ...state, value: action.foo };
    case "BAR": return { ...state, value: action.bar };
    default:
      (action: empty);
      return state;
  }
}

```
 Flow + Redux resources
----------------------

 * [Using Redux with Flow](http://frantic.im/using-redux-with-flow) - Alex Kotliarskyi
* [Redux and Flowtype](https://medium.com/@cdebotton/redux-and-flowtype-69ff1dd09036#.fsrm1amlk) - Christian de Botton



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/react/redux>

Children
========

 React elements can have zero, one, or many children. Being able to type these children with Flow allows you to build expressive APIs with React children.

 Generally, the type you should first try when adding a type for the children of your React component is [`React.Node`](../types#toc-react-node).

 Like this:

 
```
import * as React from 'react';

type Props = {
  children?: React.Node,
};

function MyComponent(props: Props) {
  return <div>{props.children}</div>;
}

```
 
>  **Note:** You need to use `import * as React from 'react'` here instead of `import React from 'react'` to get access to the [`React.Node`](../types#toc-react-node) type. We explain why that is in the [React Type Reference](../types).
> 
>  

 However, if you want to do anything more powerful with the React children API then you will need a strong intuition of how React handles children. Let us look at a couple of cases before continuing to help build that intuition.

 If you already have a strong intuition about how React children work then feel free to [skip to our examples demonstrating how to type various children patterns that commonly show up in React components](#examples).

 Our first case is an element with no children:

 
```
<MyComponent />;

// which is the same as...
React.createElement(MyComponent, {});

```
 If you pass in no children when creating an element of `MyComponent` then `props.children` will not be set. If you try to access `props.children`, it will be undefined.

 What happens when you have a single child?

 
```
<MyComponent>{42}</MyComponent>;

// which is the same as...
React.createElement(MyComponent, {}, 42);

```
 If you pass in a single value then `props.children` will be *exactly* that single value. Here `props.children` will be the number 42. Importantly, `props.children` will not be an array! It will be *exactly* the number 42.

 What happens when you have multiple children?

 
```
<MyComponent>{1}{2}</MyComponent>;

// which is the same as...
React.createElement(MyComponent, {}, 1, 2);

```
 Now, if you pass two values then `props.children` will be an array. Specifically in this case `props.children` will be `[1, 2]`.

 Multiple children may also look like:

 
```
<MyComponent>{'hello'} world</MyComponent>;

// which is the same as...
React.createElement(MyComponent, {}, 'hello', ' world');

```
 In which `props.children` would be the array `['hello', ' world']`.

 or:

 
```
<MyComponent>{'hello'} <strong>world</strong></MyComponent>;

// which is the same as...
React.createElement(
  MyComponent,
  {},
  'hello',
  ' ',
  React.createElement('strong', {}, 'world'),
);

```
 In which `props.children` would be the array `['hello', ' ', <strong>world</strong>]`.

 Moving on to the next case. What happens if we have a single child, but that child is an array?

 
```
<MyComponent>{[1, 2]}</MyComponent>;

// which is the same as...
React.createElement(MyComponent, {}, [1, 2]);

```
 This follows the same rule that when you pass in a single child then `props.children` will be *exactly* that value. Even though `[1, 2]` is an array it is a single value and so `props.children` will be *exactly* that value. That is to say `props.children` will be the array `[1, 2]` and not an array of arrays.

 This case happens often when you use `array.map()` such as in:

 
```
<MyComponent>
  {messages.map(message => <strong>{message}</strong>)}
</MyComponent>

// which is the same as...
React.createElement(
  MyComponent,
  {},
  messages.map(message => React.createElement('strong', {}, message)),
);

```
 So a single array child is left alone, but what happens if we have multiple children that are arrays?

 
```
<MyComponent>{[1, 2]}{[3, 4]}</MyComponent>;

// which is the same as...
React.createElement(MyComponent, {}, [1, 2], [3, 4]);

```
 Here `props.children` will be an array of arrays. Specifically `props.children` will be `[[1, 2], [3, 4]]`.

 The rule to remember with React children is that if you have no children then `props.children` will not be set, if you have one single child then `props.children` will be set to exactly that value, and if you have two or more children then `props.children` will be a new array of those values.

 
>  **Note:** Watch out for whitespace! Take the following:
> 
>  
> ```
> <MyComponent>{42}  </MyComponent>
> ```
>  This compiles to: `React.createElement(MyComponent, {}, 42, ' ')`. (With the spaces!) See how the spaces show up as part of the children? In this case `props.children` would be `[42, ' ']` and *not* the number 42. However, the following is fine:
> 
>  
> ```
> <MyComponent>
>   {42}
> </MyComponent>
> ```
>  It will compile to what you would expect: `React.createElement(MyComponent, {}, 42)`.
> 
>  Newlines and indentation after newlines are stripped, but watch out for whitespace when using a component with strict types around what children may be.
> 
>  

 
>  **Note:** Watch out for comments! Take the following:
> 
>  
> ```
> <MyComponent>
>   // some comment...
>   {42}
> </MyComponent>
> ```
>  This compiles to: `React.createElement(MyComponent, {}, '// some comment...', 42)`. See how the comment is included in the element’s children? In this case `props.children` would be `['// some comment...', 42]` which includes the comment. To write comments in JSX use the following syntax:
> 
>  
> ```
> <MyComponent>
>   {/* some comment... */}
>   {42}
> </MyComponent>
> ```
>  

  Now let's see how you would take this intuition and type the children of various React components. 

 Only allowing a specific element type as children.
--------------------------------------------------

 Sometimes you only want a specific component as the children to your React component. This often happens when you are building a table component which needs specific column children components, or a tab bar which needs specific configuration for each tab. One such tab bar component that uses this pattern is React Native’s `<TabBarIOS>` component.

 [React Native’s `<TabBarIOS>` component](http://facebook.github.io/react-native/docs/tabbarios.html) only allows React element children and those elements *must* have a component type of `<TabBarIOS.Item>`. You are expected to use `<TabBarIOS>` like:

 
```
<TabBarIOS>
  <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item>
  <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item>
  <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item>
</TabBarIOS>

```
 You are not allowed to do the following when using `<TabBarIOS>`:

 
```
<TabBarIOS>
  <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item>
  <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item>
  <View>{/* ... */}</View>
  <SomeOtherComponent>{/* ... */}</SomeOtherComponent>
  <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item>
</TabBarIOS>

```
 See how we added `<View>` and `<SomeOtherComponent>` as children to `<TabBarIOS>`? This is not allowed and `<TabBarIOS>` will throw an error. How do we make sure Flow does not allow this pattern?

 
```
import * as React from 'react';

class TabBarIOSItem extends React.Component<{}> {
  // implementation...
}

type Props = {
  children: React.ChildrenArray<React.Element<typeof TabBarIOSItem>>,
};

class TabBarIOS extends React.Component<Props> {
  static Item = TabBarIOSItem;
  // implementation...
}

<TabBarIOS>
  <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item>
  <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item>
  <TabBarIOS.Item>{/* ... */}</TabBarIOS.Item>
</TabBarIOS>;

```
 We set the type of props to `React.ChildrenArray<React.Element<typeof TabBarIOSItem>>` which will guarantee that `<TabBarIOS>` must only have children that are `TabBarIOS.Item` React elements.

 Our [types reference](../types) has more information about both [`React.ChildrenArray<T>`](../types#toc-react-childrenarray) and [`React.Element<typeof Component>`](../types#toc-react-element).

 
>  **Note:** If you want methods like `map()` and `forEach()` or to handle a [`React.ChildrenArray<T>`](../types#toc-react-childrenarray) as a normal JavaScript array then React provides the [`React.Children` API](https://facebook.github.io/react/docs/react-api.html#react.children) to do just this. It has functions like `React.Children.toArray(props.children)` that you can use to treat your [`React.ChildrenArray<T>`](../types#toc-react-childrenarray) as a flat array.
> 
>  

 Enforcing that a component only gets a single child.
----------------------------------------------------

 Sometimes you want to enforce that your component will *only* receive a single child. You could use [`React.Children.only()` function](https://facebook.github.io/react/docs/react-api.html#react.children.only) to enforce this constraint, but you could also enforce this in Flow. To do this, instead of wrapping the type for your children in [`React.ChildrenArray<T>`](../types#toc-react-childrenarray), specify a single element argument, like so:

 
```
import * as React from 'react';

type Props = {
  children: React.Element<any>,
};

function MyComponent(props: Props) {
  // implementation...
}

// Not allowed! You must have children.
<MyComponent />;

// Not ok! We have multiple element children.
<MyComponent>
  <div />
  <div />
  <div />
</MyComponent>;

// This is ok. We have a single element child.
<MyComponent>
  <div />
</MyComponent>;

```
 Typing function children or other exotic children types.
--------------------------------------------------------

 React allows you to pass *any* value as the children of a React component. There are some creative uses of this capability such as using a function for children which could look like this:

 
```
<MyComponent>
  {data => (
    <div>{data.foo}</div>
  )}
</MyComponent>

```
 `react-router` version 4 asks for a [function as the children to its `<Route>` component](https://reacttraining.com/react-router/core/api/Route/children-func). You would provide a function as the children to `react-router` like this:

 
```
<Route path={to}>
  {({ match }) => (
    <li className={match ? 'active' : ''}>
      <Link to={to} {...rest}/>
    </li>
  )}
</Route>

```
 (Example adapted from the [`react-router` documentation](https://reacttraining.com/react-router/core/api/Route/children-func).)

 Here is how you would type the `<Route>` component in Flow:

 
```
import * as React from 'react';

type Props = {
  children: (data: { match: boolean }) => React.Node,
  path: string,
  // other props...
};

class Route extends React.Component<Props> {
  // implementation...
}

<Route path={to}>
  {({ match }) => (
    <li className={match ? 'active' : ''}>
      <Link to={to} {...rest}/>
    </li>
  )}
</Route>;

```
 The type for `children` is a function that takes in some object type and returns a [`React.Node`](../types#toc-react-node) which is the type for any value that can be rendered by React. A `children` function does not need to return [`React.Node`](../types#toc-react-node). It could return any type, but in this case `react-router` wants to render the result returned by the `children` function.

 This pattern is also not limited to function children. You could also pass in arbitrary object or class types.

 Using `React.Node` but without some primitive types like strings.
=================================================================

 [`React.Node`](../types#toc-react-node) is the general type for children, but sometimes you might want to use [`React.Node`](../types#toc-react-node) while excluding some primitives like strings and numbers. [The React Native `<View>` component](http://facebook.github.io/react-native/docs/view.html) does this, for example.

 [The React Native `<View>` component](http://facebook.github.io/react-native/docs/view.html) will allow any primitive value or any React element as its children. However, `<View>` does not allow strings or numbers as children! You could use [`React.Node`](../types#toc-react-node) as the children type for `<View>`, however [`React.Node`](../types#toc-react-node) includes strings which we don’t want for `<View>`. So we need to create our own type.

 
```
import * as React from 'react';

type ReactNodeWithoutStrings = React.ChildrenArray<
  | void
  | null
  | boolean
  | React.Element<any>
>;

type Props = {
  children?: ReactNodeWithoutStrings,
  // other props...
};

class View extends React.Component<Props> {
  // implementation...
}

```
 [`React.ChildrenArray<T>`](../types#toc-react-childrenarray) is a type that models React nested array data structure for children. `ReactNodeWithoutStrings` uses [`React.ChildrenArray<T>`](../types#toc-react-childrenarray) to be an arbitrarily nested array of null, boolean, or React elements.

 [`React.Element<typeof Component>`](../types#toc-react-element) is the type of a React element like `<div/>` or `<MyComponent/>`. Notably elements are not the same as components!

 
>  **Note:** If you want methods like `map()` and `forEach()` or to handle a [`React.ChildrenArray<T>`](../types#toc-react-childrenarray) as a normal JavaScript array then React provides the [`React.Children` API](https://facebook.github.io/react/docs/react-api.html#react.children) to do just this. It has functions like `React.Children.toArray(props.children)` that you can use to treat your [`React.ChildrenArray<T>`](../types#toc-react-childrenarray) as a flat array.
> 
>  



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/react/children>

Type Reference
==============

 React exports a handful of utility types that may be useful to you when typing advanced React patterns. In previous sections we have seen a few of them. The following is a complete reference for each of these types along with some examples for how/where to use them.

 Table of contents:

 * [`React.Node`](#toc-react-node)
* [`React.Element<typeof Component>`](#toc-react-element)
* [`React.ChildrenArray<T>`](#toc-react-childrenarray)
* [`React.AbstractComponent<Config, Instance>`](#toc-react-abstractcomponent)
* [`React.ComponentType<Props>`](#toc-react-componenttype)
* [`React.StatelessFunctionalComponent<Props>`](#toc-react-statelessfunctionalcomponent)
* [`React.ElementType`](#toc-react-elementtype)
* [`React.Key`](#toc-react-key)
* [`React.Ref<typeof Component>`](#toc-react-ref)
* [`React.ElementProps<typeof Component>`](#toc-react-elementprops)
* [`React.ElementConfig<typeof Component>`](#toc-react-elementconfig)
* [`React.ElementRef<typeof Component>`](#toc-react-elementref)
* [`React.Config<Props, DefaultProps>`](#toc-react-config)

 These types are all exported as named type exports from the `react` module. If you want to access them as members on the `React` object (e.g. [`React.Node`](#toc-react-node) or [`React.StatelessFunctionalComponent`](#toc-react-statelessfunctionalcomponent)) and you are importing React as an ES module then you should import `React` as a namespace:

 
```
import * as React from 'react';

```
 If you are using CommonJS you can also require React:

 
```
const React = require('react');

```
 You can also use named type imports in either an ES module environment or a CommonJS environment:

 
```
import type {Node} from 'react';

```
 We will refer to all the types in the following reference as if we imported them with:

 
```
import * as React from 'react';

```
 
>  **Note:** While importing React with a default import works:
> 
>  
> ```
> import React from 'react';
> ```
>  You will have access to all of the values that React exports, but you will **not** have access to the types documented below! This is because Flow will not add types to a default export since the default export could be any value (like a number). Flow will add exported named types to an ES namespace object which you can get with `import * as React from 'react'` since Flow knows if you export a value with the same name as an exported type.
> 
>  Again, if you import React with: `import React from 'react'` you will be able to access `React.Component`, `React.createElement()`, `React.Children`, and other JavaScript *values*. However, you will not be able to access [`React.Node`](#toc-react-node), [`React.ChildrenArray`](#toc-react-childrenarray) or other Flow *types*. You will need to use a named type import like: `import type {Node} from 'react'` in addition to your default import.
> 
>  

 
`React.Node`
-------------

 This represents any node that can be rendered in a React application. `React.Node` can be null, a boolean, a number, a string, a React element, or an array of any of those types recursively.

 If you need a return type for your component `render()` methods then you should use `React.Node`. However, if you need a generic type for a children prop, use `?React.Node`; children can be undefined, when `render()` can’t return `undefined`.

 Here is an example of `React.Node` being used as the return type to `render()`:

 
```
class MyComponent extends React.Component<{}> {
  render(): React.Node {
    // ...
  }
}

```
 It may also be used as the return type of a stateless functional component:

 
```
function MyComponent(props: {}): React.Node {
  // ...
}

```
 You don’t need to annotate the return type of either your `render()` method or a stateless functional component. However, if you want to annotate the return type then `React.Node` is the generic to use.

 Here is an example of `React.Node` as the prop type for children:

 
```
function MyComponent({ children }: { children: React.Node }) {
  return <div>{children}</div>;
}

```
 All `react-dom` JSX intrinsics have `React.Node` as their children type. `<div>`, `<span>`, and all the rest.

 The definition of `React.Node` can be roughly approximated with a [`React.ChildrenArray<T>`](#toc-react-childrenarray):

 
```
type Node = React.ChildrenArray<void | null | boolean | string | number | React.Element<any>>;

```
 
`React.Element<typeof Component>`
----------------------------------

 A React element is the type for the value of a JSX element:

 
```
const element: React.Element<'div'> = <div />;

```
 `React.Element<typeof Component>` is also the return type of `React.createElement()`.

 A `React.Element<typeof Component>` takes a single type argument, `typeof Component`. `typeof Component` is the component type of the React element. For an intrinsic element, `typeof Component` will be the string literal for the intrinsic you used. Here are a few examples with DOM intrinsics:

 
```
(<div />: React.Element<'div'>); // OK
(<span />: React.Element<'span'>); // OK
(<div />: React.Element<'span'>); // Error: div is not a span.

```
 `typeof Component` can also be your React class component or stateless functional component.

 
```
class Foo extends React.Component<{}> {}
function Bar(props: {}) {}

(<Foo />: React.Element<typeof Foo>); // OK
(<Bar />: React.Element<typeof Bar>); // OK
(<Foo />: React.Element<typeof Bar>); // Error: Foo is not Bar

```
 Take note of the `typeof`, it is required! `Foo` without `typeof` would be the type of an instance of `Foo`. So: `(new Foo(): Foo)`. We want the type *of* `Foo` not the type of an instance of `Foo`. So: `(Foo: typeof Foo)`. `Class<Foo>` would also work here, but we prefer `typeof` for consistency with stateless functional components.

 We also need `typeof` for `Bar` because `Bar` is a value. So we want to get the type *of* the value `Bar`. `(Bar: Bar)` is an error because `Bar` cannot be used as a type, so the following is correct: `(Bar: typeof Bar)`.

 
`React.ChildrenArray<T>`
-------------------------

 A React children array can be a single value or an array nested to any level. It is designed to be used with the [`React.Children` API](https://reactjs.org/docs/react-api.html#reactchildren).

 For example if you want to get a normal JavaScript array from a `React.ChildrenArray<T>` see the following example:

 
```
import * as React from 'react';

// A children array can be a single value...
const children: React.ChildrenArray<number> = 42;
// ...or an arbitrarily nested array.
const children: React.ChildrenArray<number> = [[1, 2], 3, [4, 5]];

// Using the `React.Children` API can flatten the array.
const array: Array<number> = React.Children.toArray(children);

```
 
`React.AbstractComponent<Config, Instance>`
--------------------------------------------

 `React.AbstractComponent<Config, Instance>` (v0.89.0+) represents a component with a config of type Config and instance of type Instance.

 Instance is optional and is mixed by default.

 A class or function component with config `Config` may be used in places that expect `React.AbstractComponent<Config>`.

 This is Flow’s most abstract representation of a React component, and is most useful for writing HOCs and library definitions.

 
`React.ComponentType<Props>`
-----------------------------

 This is a union of a class component or a stateless functional component. This is the type you want to use for functions that receive or return React components such as higher-order components or other utilities.

 Here is how you may use `React.ComponentType<Props>` with [`React.Element<typeof Component>`](#toc-react-element) to construct a component with a specific set of props:

 
```
type Props = {
  foo: number,
  bar: number,
};

function createMyElement<C: React.ComponentType<Props>>(
  Component: C,
): React.Element<C> {
  return <Component foo={1} bar={2} />;
}

```
 `React.ComponentType<Props>` does not include intrinsic JSX element types like `div` or `span`. See [`React.ElementType`](#toc-react-elementtype) if you also want to include JSX intrinsics.

 The definition for `React.ComponentType<Props>` is roughly:

 
```
type ComponentType<Props> =
  | React.StatelessFunctionalComponent<Props>
  | Class<React.Component<Props, any>>;

```
 
>  **Note:** In 0.89.0+, React.ComponentType is an alias for React.AbstractComponent<Config, any>, which represents a component with config type Config and any instance type.
> 
>  

 
`React.StatelessFunctionalComponent<Props>`
--------------------------------------------

 This is the type of a React stateless functional component.

 The definition for `React.StatelessFunctionalComponent<Props>` is roughly:

 
```
type StatelessFunctionalComponent<Props> =
  (props: Props) => React.Node;

```
 There is a little bit more to the definition of `React.StatelessFunctionalComponent<Props>` for context and props.

 
`React.ElementType`
--------------------

 Similar to [`React.ComponentType<Props>`](#toc-react-componenttype) except it also includes JSX intrinsics (strings).

 The definition for `React.ElementType` is roughly:

 
```
type ElementType =
  | string
  | React.ComponentType<any>;

```
 
`React.MixedElement`
---------------------

 The most general type of all React elements (similar to `mixed` for all values). `React.MixedElement` is defined as `React.Element<React.ElementType>`.

 A common use case of this type is when we want to annotate an element with a type that hides the element details. For example

 
```
const element: React.MixedElement = <div />;

```
 
`React.Key`
------------

 The type of the key prop on React elements. It is a union of strings and numbers defined as:

 
```
type Key = string | number;

```
 
`React.Ref<typeof Component>`
------------------------------

 The type of the [ref prop on React elements](https://facebook.github.io/react/docs/refs-and-the-dom.html). `React.Ref<typeof Component>` could be a string or a ref function.

 The ref function will take one and only argument which will be the element instance which is retrieved using [`React.ElementRef<typeof Component>`](#toc-react-elementref) or null since [React will pass null into a ref function when unmounting](https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element).

 Like [`React.Element<typeof Component>`](#toc-react-element), `typeof Component` must be the type *of* a React component so you need to use `typeof` as in `React.Ref<typeof MyComponent>`.

 The definition for `React.Ref<typeof Component>` is roughly:

 
```
type Ref<C> =
  | string
  | (instance: React.ElementRef<C> | null) => mixed;

```
 
`React.ElementProps<typeof Component>`
---------------------------------------

 Gets the props for a React element type, *without* preserving the optionality of `defaultProps`. `typeof Component` could be the type of a React class component, a stateless functional component, or a JSX intrinsic string. This type is used for the `props` property on [`React.Element<typeof Component>`](#toc-react-element).

 Like [`React.Element<typeof Component>`](#toc-react-element), `typeof Component` must be the type *of* a React component so you need to use `typeof` as in `React.ElementProps<typeof MyComponent>`.

 
>  **Note:** Because [`React.ElementProps`](#toc-react-elementprops) does not preserve the optionality of `defaultProps`, [`React.ElementConfig`](#toc-react-elementconfig) (which does) is more often the right choice, especially for simple props pass-through as with [higher-order components](../hoc#toc-supporting-defaultprops-with-react-elementconfig).
> 
>  

 
`React.ElementConfig<typeof Component>`
----------------------------------------

 Like `React.ElementProps<typeof Component>` this utility gets the type of a component’s props but *preserves* the optionality of `defaultProps`!

 For example,

 
```
import * as React from 'react';

class MyComponent extends React.Component<{foo: number}> {
  static defaultProps = {foo: 42};

  render() {
    return this.props.foo;
  }
}

// `React.ElementProps<>` requires `foo` even though it has a `defaultProp`.
({foo: 42}: React.ElementProps<typeof MyComponent>);

// `React.ElementConfig<>` does not require `foo` since it has a `defaultProp`.
({}: React.ElementConfig<typeof MyComponent>);

```
 Like [`React.Element<typeof Component>`](#toc-react-element), `typeof Component` must be the type *of* a React component so you need to use `typeof` as in `React.ElementProps<typeof MyComponent>`.

 
`React.ElementRef<typeof Component>`
-------------------------------------

 Gets the instance type for a React element. The instance will be different for various component types:

 * React class components will be the class instance. So if you had `class Foo extends React.Component<{}> {}` and used `React.ElementRef<typeof Foo>` then the type would be the instance of `Foo`.
* React stateless functional components do not have a backing instance and so `React.ElementRef<typeof Bar>` (when `Bar` is `function Bar() {}`) will give you the undefined type.
* JSX intrinsics like `div` will give you their DOM instance. For `React.ElementRef<'div'>` that would be `HTMLDivElement`. For `React.ElementRef<'input'>` that would be `HTMLInputElement`.

 Like [`React.Element<typeof Component>`](#toc-react-element), `typeof Component` must be the type *of* a React component so you need to use `typeof` as in `React.ElementRef<typeof MyComponent>`.

 
`React.Config<Props, DefaultProps>`
------------------------------------

 Calculates a config object from props and default props. This is most useful for annotating HOCs that are abstracted over configs. See our [docs on writing HOCs](../hoc) for more information.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/react/types>

Primitive Types
===============

 JavaScript has a number of different primitive types ([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures)):

 * Booleans
* Strings
* Numbers
* `null`
* `undefined` (`void` in Flow types)
* Symbols (new in ECMAScript 2015)

 The primitive types appear in the language as either literal values.

 
```
true;
"hello";
3.14;
null;
undefined;

```
 Or as constructed wrapper objects.

 
```
new Boolean(false);
new String("world");
new Number(42);

```
 Types for literal values are lowercase.

 
```
// @flow
function method(x: number, y: string, z: boolean) {
  // ...
}

method(3.14, "hello", true);

```
 Types for the wrapper objects are capitalized (the same as their constructor).

 
```
// @flow
function method(x: Number, y: String, z: Boolean) {
  // ...
}

method(new Number(42), new String("world"), new Boolean(false));

```
 These wrapper objects are rarely used.

 Booleans
--------

 Booleans are `true` and `false` values in JavaScript. The `boolean` type in Flow accepts these values.

 
```
// @flow
function acceptsBoolean(value: boolean) {
  // ...
}

acceptsBoolean(true);  // Works!
acceptsBoolean(false); // Works!
acceptsBoolean("foo"); // Error!

```
 JavaScript can also implicitly convert other types of values into booleans.

 
```
if (42) {} // 42 => true
if ("") {} // "" => false

```
 Flow understands these conversions and will allow any of them as part of an `if` statement and other types of expressions.

 Boolean types need you to be explicit by converting non-booleans. You can do that with `Boolean(x)` or `!!x`.

 
```
// @flow
function acceptsBoolean(value: boolean) {
  // ...
}

acceptsBoolean(0);          // Error!
acceptsBoolean(Boolean(0)); // Works!
acceptsBoolean(!!0);        // Works!

```
 Remember that `boolean` and `Boolean` are different types.

 * A `boolean` is a literal value like `true` or `false` or the result of an expression like `a === b`.
* A `Boolean` is a wrapper object created by the global `new Boolean(x)` constructor.

 Numbers
-------

 Unlike many other languages, JavaScript only has one type of number. These values may appear as `42` or `3.14`. JavaScript also considers `Infinity` and `NaN` to be numbers. The `number` type captures everything JavaScript considers a number.

 
```
// @flow
function acceptsNumber(value: number) {
  // ...
}

acceptsNumber(42);       // Works!
acceptsNumber(3.14);     // Works!
acceptsNumber(NaN);      // Works!
acceptsNumber(Infinity); // Works!
acceptsNumber("foo");    // Error!

```
 Remember that `number` and `Number` are different types.

 * A `number` is a literal value like `42` or `3.14` or the result of an expression like `parseFloat(x)`.
* A `Number` is a wrapper object created by the global `new Number(x)` constructor.

 Strings
-------

 Strings are `"foo"` values in JavaScript. The `string` type in Flow accepts these values.

 
```
// @flow
function acceptsString(value: string) {
  // ...
}

acceptsString("foo"); // Works!
acceptsString(false); // Error!

```
 JavaScript implicitly converts other types of values into strings by concatenating them.

 
```
"foo" + 42; // "foo42"
"foo" + {}; // "foo[object Object]"

```
 Flow will only accept strings and number when concatenating them to strings.

 
```
// @flow
"foo" + "foo"; // Works!
"foo" + 42;    // Works!
"foo" + {};    // Error!
"foo" + [];    // Error!

```
 You must be explicit and convert other types into strings. You can do this by using the String method or using another method for stringifying values.

 
```
// @flow
"foo" + String({});     // Works!
"foo" + [].toString();  // Works!
"" + JSON.stringify({}) // Works!

```
 Remember that `string` and `String` are different types.

 * A `string` is a literal value like `"foo"` or the result of an expression like `"" + 42`.
* A `String` is a wrapper object created by the global `new String(x)` constructor.

 
`null` and `void`
------------------

 JavaScript has both `null` and `undefined`. Flow treats these as separate types: `null` and `void` (for `undefined`).

 
```
// @flow
function acceptsNull(value: null) {
  /* ... */
}

function acceptsUndefined(value: void) {
  /* ... */
}

acceptsNull(null);      // Works!
acceptsNull(undefined); // Error!
acceptsUndefined(null);      // Error!
acceptsUndefined(undefined); // Works!

```
 `null` and `void` also appear in other types.

 ### Maybe types

 Maybe types are for places where a value is optional and you can create them by adding a question mark in front of the type such as `?string` or `?number`.

 In addition to the `type` in `?type`, maybe types can also be `null` or `void`.

 
```
// @flow
function acceptsMaybeString(value: ?string) {
  // ...
}

acceptsMaybeString("bar");     // Works!
acceptsMaybeString(undefined); // Works!
acceptsMaybeString(null);      // Works!
acceptsMaybeString();          // Works!

```
 ### Optional object properties

 Object types can have optional properties where a question mark `?` comes after the property name.

 
```
{ propertyName?: string }

```
 In addition to their set value type, these optional properties can either be `void` or omitted altogether. However, they cannot be `null`.

 
```
// @flow
function acceptsObject(value: { foo?: string }) {
  // ...
}

acceptsObject({ foo: "bar" });     // Works!
acceptsObject({ foo: undefined }); // Works!
acceptsObject({ foo: null });      // Error!
acceptsObject({});                 // Works!

```
 ### Optional function parameters

 Functions can have optional parameters where a question mark `?` comes after the parameter name.

 
```
function method(param?: string) { /* ... */ }

```
 In addition to their set type, these optional parameters can either be `void` or omitted altogether. However, they cannot be `null`.

 
```
// @flow
function acceptsOptionalString(value?: string) {
  // ...
}

acceptsOptionalString("bar");     // Works!
acceptsOptionalString(undefined); // Works!
acceptsOptionalString(null);      // Error!
acceptsOptionalString();          // Works!

```
 ### Function parameters with defaults

 Function parameters can also have defaults. This is a feature of ECMAScript 2015.

 
```
function method(value: string = "default") { /* ... */ }

```
 In addition to their set type, default parameters can also be `void` or omitted altogether. However, they cannot be `null`.

 
```
// @flow
function acceptsOptionalString(value: string = "foo") {
  // ...
}

acceptsOptionalString("bar");     // Works!
acceptsOptionalString(undefined); // Works!
acceptsOptionalString(null);      // Error!
acceptsOptionalString();          // Works!

```
 Symbols
-------

 Symbols are created with `Symbol()` in JavaScript. Flow has basic support for symbols, using the `symbol` type.

 
```
// @flow
function acceptsSymbol(value: symbol) {
  // ...
}

acceptsSymbol(Symbol()); // Works!
acceptsSymbol(Symbol.isConcatSpreadable); // Works!
acceptsSymbol(false); // Error!

```
 You can use `typeof x === "symbol"` to refine to a symbol.

 
```
const x: symbol | number = Symbol();
if (typeof x === "symbol") {
  const y: symbol = x;
} else {
  const z: number = x;
}
```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/primitives>

Mixed Types
===========

 In general, programs have several different categories of types:

 **A single type:**

 Here the input value can only be a `number`.

 
```
function square(n: number) {
  return n * n;
}

```
 **A group of different possible types:**

 Here the input value could be either a `string` or a `number`.

 
```
function stringifyBasicValue(value: string | number) {
  return '' + value;
}

```
 **A type based on another type:**

 Here the return type will be the same as the type of whatever value is passed into the function.

 
```
function identity<T>(value: T): T {
  return value;
}

```
 These three are the most common categories of types. They will make up the majority of the types you’ll be writing.

 However, there is also a fourth category.

 **An arbitrary type that could be anything:**

 Here the passed in value is an unknown type, it could be any type and the function would still work.

 
```
function getTypeOf(value: mixed): string {
  return typeof value;
}

```
 These unknown types are less common, but are still useful at times.

 You should represent these values with `mixed`.

 Anything goes in, Nothing comes out
-----------------------------------

 `mixed` will accept any type of value. Strings, numbers, objects, functions– anything will work.

 
```
// @flow
function stringify(value: mixed) {
  // ...
}

stringify("foo");
stringify(3.14);
stringify(null);
stringify({});

```
 When you try to use a value of a `mixed` type you must first figure out what the actual type is or you’ll end up with an error.

 
```
// @flow
function stringify(value: mixed) {
  // $ExpectError
  return "" + value; // Error!
}

stringify("foo");

```
 Instead you must ensure the value is a certain type by refining it.

 
```
// @flow
function stringify(value: mixed) {
  if (typeof value === 'string') {
    return "" + value; // Works!
  } else {
    return "";
  }
}

stringify("foo");

```
 Because of the `typeof value === 'string'` check, Flow knows the `value` can only be a `string` inside of the `if` statement. This is known as a [refinement](https://flow.org/en/lang/refinements/).



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/mixed>

Higher-order Components
=======================

 A popular pattern in React is the [higher-order component pattern](https://facebook.github.io/react/docs/higher-order-components.html), so it’s important that we can provide effective types for higher-order components in Flow. If you don’t already know what a higher-order component is then make sure to read the [React documentation on higher-order components](https://facebook.github.io/react/docs/higher-order-components.html) before continuing.

 In 0.89.0, we introduced [`React.AbstractComponent`](../types#toc-react-abstractcomponent), which gives you more expressive power when writing HOCs and library definitions.

 Let’s take a look at how you can type some example HOCs.

 The Trivial HOC
---------------

 Let’s start with the simplest HOC:

 
```
//@flow
import * as React from 'react';

function trivialHOC<Config: {}>(
  Component: React.AbstractComponent<Config>
): React.AbstractComponent<Config> {
  return Component;
}

```
 This is a basic template for what your HOCs might look like. At runtime, this HOC doesn’t do anything at all. Let’s take a look at some more complex examples.

 Injecting Props
---------------

 A common use case for higher-order components is to inject a prop. The HOC automatically sets a prop and returns a component which no longer requires that prop. For example, consider a navigation prop, or in the case of [`react-redux` a `store` prop](https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options). How would one type this?

 To remove a prop from the config, we can take a component that includes the prop and return a component that does not. It’s best to construct these types using object type spread.

 
```
//@flow
import * as React from 'react';

type InjectedProps = {| foo: number |}

function injectProp<Config>(
  Component: React.AbstractComponent<{| ...Config, ...InjectedProps |}>
): React.AbstractComponent<Config> {
  return function WrapperComponent(
    props: Config,
  ) {
    return <Component {...props} foo={42} />;
  };
}

class MyComponent extends React.Component<{|
  a: number,
  b: number,
  ...InjectedProps,
|}> {}

const MyEnhancedComponent = injectProp(MyComponent);

// We don't need to pass in `foo` even though `MyComponent` requires it.
<MyEnhancedComponent a={1} b={2} />;

```
 Preserving the Instance Type of a Component
-------------------------------------------

 Recall that the instance type of a function component is `void`. Our example above wraps a component in a function, so the returned component has the instance type `void`.

 
```
//@flow
import * as React from 'react';

type InjectedProps = {| foo: number |}

function injectProp<Config>(
  Component: React.AbstractComponent<{| ...Config, ...InjectedProps |}>
): React.AbstractComponent<Config> {
  return function WrapperComponent(
    props: Config,
  ) {
    return <Component {...props} foo={42} />;
  };
}

class MyComponent extends React.Component<{|
  a: number,
  b: number,
  ...InjectedProps,
|}> {}

const MyEnhancedComponent = injectProp(MyComponent);

// If we create a ref object for the component, it will never be assigned
// an instance of MyComponent!
const ref = React.createRef<MyComponent>();

// Error, mixed is incompatible with MyComponent.
<MyEnhancedComponent ref={ref} a={1} b={2} />;

```
 We get this error message because `React.AbstractComponent<Config>` doesn’t set the `Instance` type parameter, so it is automatically set to `mixed`. If we wanted to preserve the instance type of the component, we can use [`React.forwardRef`](https://reactjs.org/docs/forwarding-refs.html):

 
```
//@flow
import * as React from 'react';

type InjectedProps = {| foo: number |}

function injectAndPreserveInstance<Config, Instance>(
  Component: React.AbstractComponent<{| ...Config, ...InjectedProps |}, Instance>
): React.AbstractComponent<Config, Instance> {
  return React.forwardRef<Config, Instance>((props, ref) =>
      <Component ref={ref} foo={3} {...props} />
  );
}

class MyComponent extends React.Component<{
  a: number,
  b: number,
  ...InjectedProps,
}> {}

const MyEnhancedComponent = injectAndPreserveInstance(MyComponent);

const ref = React.createRef<MyComponent>();

// All good! The ref is forwarded.
<MyEnhancedComponent ref={ref} a={1} b={2} />;

```
 Exporting Wrapped Components
----------------------------

 If you try to export a wrapped component, chances are that you’ll run into a missing annotation error:

 
```
//@flow
import * as React from 'react';

function trivialHOC<Config: {}>(
  Component: React.AbstractComponent<Config>,
): React.AbstractComponent<Config> {
  return Component;
}

type DefaultProps = {| foo: number |};
type Props = {...DefaultProps, bar: number};

class MyComponent extends React.Component<Props> {
  static defaultProps: DefaultProps = {foo: 3};
}

// Error, missing annotation for Config.
const MyEnhancedComponent = trivialHOC(MyComponent);

module.exports = MyEnhancedComponent;

```
 If your component has no `defaultProps`, you can use `Props` as a type argument for `Config`.

 If your component does have `defaultProps`, you don’t want to just add `Props` as a type argument to `trivialHOC` because that will get rid of the `defaultProps` information that flow has about your component.

 This is where [`React.Config<Props, DefaultProps>`](../types#toc-react-config) comes in handy! We can use the type for Props and DefaultProps to calculate the `Config` type for our component.

 
```
//@flow
import * as React from 'react';

function trivialHOC<Config: {}>(
  Component: React.AbstractComponent<Config>,
): React.AbstractComponent<Config> {
  return Component;
}

type DefaultProps = {| foo: number |};
type Props = {...DefaultProps, bar: number};

class MyComponent extends React.Component<Props> {
  static defaultProps: DefaultProps = {foo: 3};
}

const MyEnhancedComponent = trivialHOC<React.Config<Props, DefaultProps>>(MyComponent);

// Ok!
module.exports = MyEnhancedComponent;

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/react/hoc>

IDE Integration
===============

 In most editors, Flow warnings are likely to be rendered the same way as other warnings are rendered by that editor.

 Most editors will likely display all Flow warnings, which is fine for small- to medium-scale projects, or projects with fewer unsuppressed warnings.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/linting/ide-integration>

Literal Types
=============

 Flow has [primitive types](../primitives) for literal values, but can also use literal values as types.

 For example, instead of accepting `number` type, we could accept only the literal value `2`.

 
```
// @flow
function acceptsTwo(value: 2) {
  // ...
}

acceptsTwo(2);   // Works!
// $ExpectError
acceptsTwo(3);   // Error!
// $ExpectError
acceptsTwo("2"); // Error!

```
 You can use primitive values for these types:

 * Booleans: like `true` or `false`
* Numbers: like `42` or `3.14`
* Strings: like `"foo"` or `"bar"`

 Using these with [union types](../unions) is powerful:

 
```
// @flow
function getColor(name: "success" | "warning" | "danger") {
  switch (name) {
    case "success" : return "green";
    case "warning" : return "yellow";
    case "danger"  : return "red";
  }
}

getColor("success"); // Works!
getColor("danger");  // Works!
// $ExpectError
getColor("error");   // Error!

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/literals>

Any Types
=========

 
>  **Warning:** Do not mistake `any` with `mixed`. [Read more](../mixed)
> 
>  

 If you want a way to opt-out of using the type checker, `any` is the way to do it. **Using `any` is completely unsafe, and should be avoided whenever possible.**

 For example, the following code will not report any errors:

 
```
// @flow
function add(one: any, two: any): number {
  return one + two;
}

add(1, 2);     // Works.
add("1", "2"); // Works.
add({}, []);   // Works.

```
 Even code that will cause runtime errors will not be caught by Flow:

 
```
// @flow
function getNestedProperty(obj: any) {
  return obj.foo.bar.baz;
}

getNestedProperty({});

```
 There are only a couple of scenarios where you might consider using `any`:

 1. When you are in the process of converting existing code to using Flow types and you are currently blocked on having the code type checked (maybe other code needs to be converted first).
2. When you are certain your code works and for some reason Flow is unable to type check it correctly. There are a (decreasing) number of idioms in JavaScript that Flow is unable to statically type.

 Avoid leaking `any`
-------------------

 When you have a value with the type `any`, you can cause Flow to infer `any` for the results of all of the operations you perform.

 For example, if you get a property on an object typed `any`, the resulting value will also have the type `any`.

 
```
// @flow
function fn(obj: any) {
  let foo /* (:any) */ = obj.foo;
}

```
 You could then use the resulting value in another operation, such as adding it as if it were a number and the result will also be `any`.

 
```
// @flow
function fn(obj: any) {
  let foo /* (:any) */ = obj.foo;
  let bar /* (:any) */ = foo * 2;
}

```
 You could continue this process until `any` has leaked all over your code.

 
```
// @flow
function fn(obj: any) /* (:any) */ {
  let foo /* (:any) */ = obj.foo;
  let bar /* (:any) */ = foo * 2;
  return bar;
}

let bar /* (:any) */ = fn({ foo: 2 });
let baz /* (:any) */ = "baz:" + bar;

```
 Prevent this from happening by cutting `any` off as soon as possible by casting it to another type.

 
```
// @flow
function fn(obj: any) {
  let foo: number = obj.foo;
}

```
 Now your code will not leak `any`.

 
```
// @flow
function fn(obj: any) /* (:number) */ {
  let foo: number = obj.foo;
  let bar /* (:number) */ = foo * 2;
  return bar;
}

let bar /* (:number) */ = fn({ foo: 2 });
let baz /* (:string) */ = "baz:" + bar;

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/any>

Tuple Types
===========

 Tuples are a sort of list but with a limited set of items. In JavaScript, tuples are created using arrays.

 In Flow you can create tuples using the `[type, type, type]` syntax.

 
```
let tuple1: [number] = [1];
let tuple2: [number, boolean] = [1, true];
let tuple3: [number, boolean, string] = [1, true, "three"];

```
 When you are getting a value from a tuple at a specific index, it will return the type at that index.

 
```
// @flow
let tuple: [number, boolean, string] = [1, true, "three"];

let num  : number  = tuple[0]; // Works!
let bool : boolean = tuple[1]; // Works!
let str  : string  = tuple[2]; // Works!

```
 Trying to access an index that does not exist results in an index-out-of-bounds error.

 
```
// @flow
let tuple: [number, boolean, string] = [1, true, "three"];

let none = tuple[3]; // Error!

```
 If Flow doesn’t know which index you are trying to access it will return all possible types.

 
```
// @flow
let tuple: [number, boolean, string] = [1, true, "three"];

function getItem(n: number) {
  let val: number | boolean | string = tuple[n];
  // ...
}

```
 When setting a new value inside a tuple, the new value must match the type at that index.

 
```
// @flow
let tuple: [number, boolean, string] = [1, true, "three"];

tuple[0] = 2;     // Works!
tuple[1] = false; // Works!
tuple[2] = "foo"; // Works!

// $ExpectError
tuple[0] = "bar"; // Error!
// $ExpectError
tuple[1] = 42;    // Error!
// $ExpectError
tuple[2] = false; // Error!

```
 Strictly enforced tuple length (arity)
--------------------------------------

 The length of the tuple is known as the “arity”. The length of a tuple is strictly enforced in Flow.

 #### Tuples only match tuples with same length

 This means that a shorter tuple can’t be used in place of a longer one.

 
```
// @flow
let tuple1: [number, boolean]       = [1, true];
// $ExpectError
let tuple2: [number, boolean, void] = tuple1; // Error!

```
 Also, a longer tuple can’t be used in place of a shorter one.

 
```
// @flow
let tuple1: [number, boolean, void] = [1, true];
// $ExpectError
let tuple2: [number, boolean]       = tuple1; // Error!

```
 #### Tuples don’t match array types

 Since Flow does not know the length of an array, an `Array<T>` type cannot be passed into a tuple.

 
```
// @flow
let array: Array<number>    = [1, 2];
// $ExpectError
let tuple: [number, number] = array; // Error!

```
 Also a tuple type cannot be passed into to an `Array<T>` type, since then you could mutate the tuple in an unsafe way.

 
```
// @flow
let tuple: [number, number] = [1, 2];
// $ExpectError
let array: Array<number>    = tuple; // Error!

```
 #### Cannot use mutating array methods on tuples

 You cannot use `Array.prototype` methods that mutate the tuple, only ones that do not.

 
```
// @flow
let tuple: [number, number] = [1, 2];
tuple.join(', '); // Works!
// $ExpectError
tuple.push(3);    // Error!

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/tuples>

Flowlint Comments
=================

 Configuring lint settings with `flowlint` comments allows you to specify different settings within a file and different settings to different regions of different files. These comments come in three forms:

 * [flowlint](#toc-flowlint)
* [flowlint-line](#toc-flowlint-line)
* [flowlint-next-line](#toc-flowlint-next-line)

 In all forms, whitespace and asterisks between words are ignored, allowing for flexible formatting.

 flowlint
--------

 The basic `flowlint` comment takes a comma-delimited list of `rule:severity` pairs and applies those settings for the rest of the source file until overridden. This has three primary purposes: applying settings over a block, applying settings over a file, and applying settings over part of a line.

 **settings over a block of code:** A pair of `flowlint` comments can be used to apply a certain setting over a block of code. For example, to disabling the untyped-type-import lint over a block of type imports would look like this:

 
```
import type {
  // flowlint untyped-type-import:off
  Foo,
  Bar,
  Baz,
  // flowlint untyped-type-import:error
} from './untyped.js';

```
 **settings over a file:** A `flowlint` comment doesn’t have to have a matching comment to form a block. An unmatched comment simply applies its settings to the rest of the file. You could use this, for example, to suppress all sketchy-null-check lints in a particular file:

 
```
// flowlint sketchy-null:off
...

```
 **settings over part of a line:** The settings applied by `flowlint` start and end right at the comment itself. This means that you can do things like

 
```
function (a: ?boolean, b: ?boolean) {
  if (/* flowlint sketchy-null-bool:off */a/* flowlint sketchy-null-bool:warn */ && b) {
    ...
  } else {
    ...
  }
}

```
 if you want control at an even finer level than you get from the line-based comments.

 flowlint-line
-------------

 A `flowlint-line` comment works similarly to a `flowlint` comment, except it only applies its settings to the current line instead of applying them for the rest of the file. The primary use for `flowlint-line` comments is to suppress a lint on a particular line:

 
```
function (x: ?boolean) {
  if (x) { // flowlint-line sketchy-null-bool:off
    ...
  } else {
    ...
  }
}

```
 flowlint-next-line
------------------

 `flowlint-next-line` works the same as `flowlint-line`, except it applies its settings to the next line instead of the current line:

 
```
function (x: ?boolean) {
  // flowlint-next-line sketchy-null-bool:off
  if (x) {
    ...
  } else {
    ...
  }
}

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/linting/flowlint-comments>

Class Types
===========

 JavaScript [classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) in Flow operate both as a value and a type.

 You write classes the same way you would without Flow, but then you can use the name of the class as a type.

 
```
class MyClass {
  // ...
}

let myInstance: MyClass = new MyClass();

```
 This is because classes in Flow are [nominally typed](https://flow.org/en/lang/nominal-structural).

 Class Syntax
------------

 Classes in Flow are identical to normal JavaScript classes, but with added types.

 #### Class Methods

 Just like in functions, class methods can have annotations for both parameters (input) and returns (output).

 
```
class MyClass {
  method(value: string): number { /* ... */ }
}

```
 Also just like regular functions, class methods may have `this` annotations as well. However, if one is not provided, Flow will infer the class instance type (or the class type for static methods) instead of `mixed`. When an explicit `this` parameter is provided, it must be a [supertype](https://flow.org/en/lang/subtypes/) of the class instance type (or class type for static methods).

 
```
class MyClass {
  method(this : interface { x : string }): void { /* ... */ } // x is missing in `MyClass`
}

```
 Unlike class properties, however, class methods cannot be unbound or rebound from the class on which you defined them. So all of the following are errors in Flow:

 
```
let c = new MyClass();
c.method;
let {method} = c;
c.method.bind({});

```
 #### Class Fields (Properties)

 Whenever you want to use a class field in Flow you must first give it an annotation.

 
```
// @flow
class MyClass {
  method() {
    // $ExpectError
    this.prop = 42; // Error!
  }
}

```
 Fields are annotated within the body of the class with the field name followed by a colon `:` and the type.

 
```
// @flow
class MyClass {
  prop: number;
  method() {
    this.prop = 42;
  }
}

```
 Fields added outside of the class definition need to be annotated within the body of the class.

 
```
// @flow
function func_we_use_everywhere (x: number): number {
  return x + 1;
}
class MyClass {
  static constant: number;
  static helper: (number) => number;
  function_property: number => number;
}
MyClass.helper = func_we_use_everywhere
MyClass.constant = 42
MyClass.prototype.function_property = func_we_use_everywhere

```
 Flow also supports using the [class properties syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#field_declarations).

 
```
class MyClass {
  prop = 42;
}

```
 When using this syntax, you are not required to give it a type annotation. But you still can if you need to.

 
```
class MyClass {
  prop: number = 42;
}

```
 #### Class Constructors

 You can initialize your class properties in class constructors.

 
```
class MyClass {
  foo: number;

  constructor() {
    this.foo = 1;
  }
}

```
 You must first call `super(...)` in a derived class before you can access `this` and `super`.

 
```
class Base {
  bar: number;
}
class MyClass extends Base {
  foo: number;

  constructor() {
    this.foo; // Error
    this.bar; // Error
    super.bar; // Error
    super();
    this.foo; // OK
    this.bar; // OK
    super.bar; // OK
  }
}

```
 However, Flow will not enforce that all class properties are initialized in constructors.

 
```
class MyClass {
  foo: number;
  bar: number;

  constructor() {
    this.foo = 1;
  }

  useBar() {
    (this.bar: number); // No errors.
  }
}

```
 #### Class Generics

 Classes can also have their own [generics](../generics).

 
```
class MyClass<A, B, C> {
  property: A;
  method(val: B): C {
    // ...
  }
}

```
 Class generics are [parameterized](../generics#toc-parameterized-generics). When you use a class as a type you need to pass parameters for each of its generics.

 
```
// @flow
class MyClass<A, B, C> {
  constructor(arg1: A, arg2: B, arg3: C) {
    // ...
  }
}

var val: MyClass<number, boolean, string> = new MyClass(1, true, 'three');

```
 Classes in annotations
----------------------

 When you use the name of your class in an annotation, it means an *instance* of your class:

 
```
//@flow
class MyClass {}
(MyClass: MyClass); // Error
(new MyClass(): MyClass); // Ok

```
 See [here](../utilities#toc-class) for details on `Class<T>`, which allows you to refer to the type of the class in an annotation.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/classes>

Array Types
===========

 
>  **Note:** Arrays are also sometimes used as tuples in JavaScript, these are annotated differently in Flow. See the Tuple docs for more information.
> 
>  

 Arrays are a special list-like type of object in JavaScript. You can create arrays a couple different ways.

 
```
new Array(1, 2, 3); // [1, 2, 3];
new Array(3);       // [undefined, undefined, undefined]
[1, 2, 3];          // [1, 2, 3];

```
 You can also create arrays and add values to them later on:

 
```
let arr = []; // []
arr[0] = 1;   // [1]
arr[1] = 2;   // [1, 2]
arr[2] = 3;   // [1, 2, 3]

```
 
`Array` Type
-------------

 To create an array type you can use `Array<Type>` type where `Type` is the type of elements in the array. For example, to create a type for an array of numbers you use `Array<number>`.

 
```
let arr: Array<number> = [1, 2, 3];

```
 You can put any type within `Array<Type>`.

 
```
let arr1: Array<boolean> = [true, false, true];
let arr2: Array<string> = ["A", "B", "C"];
let arr3: Array<mixed> = [1, true, "three"]

```
 
`Array` Type Shorthand Syntax
------------------------------

 There’s also a slightly shorter form of this syntax: `Type[]`.

 
```
let arr: number[] = [0, 1, 2, 3];

```
 Just note that `?Type[]` is the equivalent of `?Array<T>` and not `Array<?T>`.

 
```
// @flow
let arr1: ?number[] = null;   // Works!
let arr2: ?number[] = [1, 2]; // Works!
let arr3: ?number[] = [null]; // Error!

```
 If you want to make it `Array<?T>` you can use parenthesis like: `(?Type)[]`

 
```
// @flow
let arr1: (?number)[] = null;   // Error!
let arr2: (?number)[] = [1, 2]; // Works!
let arr3: (?number)[] = [null]; // Works!

```
 Array access is unsafe
----------------------

 When you retrieve an element from an array there is always a possibility that it is `undefined`. You could have either accessed an index which is out of the bounds of the array, or the element could not exist because it is a “sparse array”.

 For example, you could be accessing an element that is out of the bounds of the array.

 
```
// @flow
let array: Array<number> = [0, 1, 2];
let value: number = array[3]; // Works.
                       // ^ undefined

```
 Or you could be accessing an element that does not exist if it is a “sparse array”.

 
```
// @flow
let array: Array<number> = [];

array[0] = 0;
array[2] = 2;

let value: number = array[1]; // Works.
                       // ^ undefined

```
 In order to make this safe, Flow would have to mark every single array access as “*possibly undefined”*.

 Flow does not do this because it would be extremely inconvenient to use. You would be forced to refine the type of every value you get when accessing an array.

 
```
let array: Array<number> = [0, 1, 2];
let value: number | void = array[1];

if (value !== undefined) {
  // number
}

```
 As Flow is made to be smarter it may be possible in the future to fix this problem, but for now you should be aware of it.

 
`$ReadOnlyArray<T>`
--------------------

 Similar to [`$ReadOnly<T>`](../utilities#toc-readonly), it is the supertype of all arrays and all tuples and represents a read-only view of an array. It does not contain any methods that will allow an object of this type to be mutated (no `push()`, `pop()`, etc.).

 
```
// @flow
const readonlyArray: $ReadOnlyArray<number> = [1, 2, 3]

const first = readonlyArray[0] // OK to read
readonlyArray[1] = 20          // Error!
readonlyArray.push(4)          // Error!

```
 Note that an array of type `$ReadOnlyArray<T>` can still have mutable *elements*:

 
```
// @flow
const readonlyArray: $ReadOnlyArray<{x: number}> = [{x: 1}];
readonlyArray[0] = {x: 42}; // Error!
readonlyArray[0].x = 42; // OK

```
 The main advantage to using `$ReadOnlyArray` instead of `Array` is that `$ReadOnlyArray`’s type parameter is *covariant* while `Array`’s type parameter is *invariant*. That means that `$ReadOnlyArray<number>` is a subtype of `$ReadOnlyArray<number | string>` while `Array<number>` is NOT a subtype of `Array<number | string>`. So it’s often useful to use `$ReadOnlyArray` in type annotations for arrays of various types of elements. Take, for instance, the following scenario:

 
```
// @flow
const someOperation = (arr: Array<number | string>) => {
  // Here we could do `arr.push('a string')`
}

const array: Array<number> = [1]
someOperation(array) // Error!

```
 Since the parameter `arr` of the `someOperation` function is typed as a mutable `Array`, pushing a string into it would be possible inside that scope, which would then break the type contract of the outside `array` variable. By annotating the parameter as `$ReadOnlyArray` instead in this case, Flow can be sure this won’t happen and no errors will occur:

 
```
// @flow
const someOperation = (arr: $ReadOnlyArray<number | string>) => {
  // Nothing can be added to `arr`
}

const array: Array<number> = [1]
someOperation(array) // Works!

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/arrays>

Lint Rule Reference
===================

 Available Lint Rules
--------------------

 * [`all`](#toc-all)
* [`ambiguous-object-type`](#toc-ambiguous-object-type)
* [`deprecated-type`](#toc-deprecated-type)
* [`deprecated-utility`](#toc-deprecated-utility)
* [`implicit-inexact-object`](#toc-implicit-inexact-object)
* [`nonstrict-import`](#toc-nonstrict-import)
* [`sketchy-null`](#toc-sketchy-null)
* [`sketchy-number`](#toc-sketchy-number)
* [`unclear-type`](#toc-unclear-type)
* [`unnecessary-invariant`](#toc-unnecessary-invariant)
* [`unnecessary-optional-chain`](#toc-unnecessary-optional-chain)
* [`unsafe-getters-setters`](#toc-unsafe-getters-setters)
* [`untyped-import`](#toc-untyped-import)
* [`untyped-type-import`](#toc-untyped-type-import)

 ### 
`all`

 While `all` isn’t technically a lint rule, it’s worth mentioning here. `all` sets the default level for lint rules that don’t have a level set explicitly. `all` can only occur as the first entry in a `.flowconfig` or as the first rule in a `--lints` flag. It’s not allowed in comments at all because it would have different semantics than would be expected.

 ### 
`ambiguous-object-type`

 Like [`implicit-inexact-object`](#toc-implicit-inexact-object), except triggers even when the `exact_by_default` option is set to `true`.

 ### 
`deprecated-type`

 Triggers when you use the `*` (existential) type, as this type is unsafe and usually just equivalent to `any`. The effect of `*` can generally be achieved by simply not providing a type annotation.

 ### 
`deprecated-utility`

 Triggers when you use the `$Supertype` or `$Subtype` utility types, as these types are unsafe and equivalent to `any`.

 ### 
`implicit-inexact-object`

 Triggers when you use object type syntax without explicitly specifying exactness or inexactness.

 This lint setting is ignored when `exact_by_default` is set to `true`.

 
```
type A = {x: number}; // Error
type B = {x: number, ...} // Ok
type C = {| x: number |} // Ok
```
 ### 
`nonstrict-import`

 Used in conjuction with [Flow Strict](https://flow.org/en/strict/). Triggers when importing a non `@flow strict` module. When enabled, dependencies of a `@flow strict` module must also be `@flow strict`.

 ### 
`sketchy-null`

 Triggers when you do an existence check on a value that can be either null/undefined or falsey.

 For example:

 
```
const x: ?number = 5;
if (x) {} // sketchy because x could be either null or 0.

const y: number = 5;
if (y) {} // not sketchy because y can't be null, only 0.

const z: ?{foo: number} = {foo: 5};
if (z) {} // not sketchy, because z can't be falsey, only null/undefined.

```
 Setting `sketchy-null` sets the level for all sketchy null checks, but there are more granular rules for particular types. These are:

 * `sketchy-null-bool`
* `sketchy-null-number`
* `sketchy-null-string`
* `sketchy-null-mixed`

 The type-specific variants are useful for specifying that some types of sketchy null checks are acceptable while others should be errors/warnings. For example, if you want to allow boolean sketchy null checks (for the pattern of treating undefined optional booleans as false) but forbid other types of sketchy null checks, you can do so with this `.flowconfig` `[lints]` section:

 
```
[lints]
sketchy-null=warn
sketchy-null-bool=off
```
 and now

 
```
function foo (bar: ?bool): void {
  if (bar) {
    ...
  } else {
    ...
  }
}

```
 doesn’t report a warning.

 Suppressing one type of sketchy null check only suppresses that type, so, for example

 
```
// flowlint sketchy-null:warn, sketchy-null-bool:off
const x: ?(number | bool) = 0;
if (x) {}

```
 would still have a sketchy-null-number warning on line 3.

 ### 
`sketchy-number`

 Triggers when a `number` is used in a manner which may lead to unexpected results if the value is falsy. Currently, this lint triggers if a `number` appears in:

 * the left-hand side of an `&&` expression.

 As a motivating example, consider this common idiom in React:

 
```
{showFoo && <Foo />}

```
 Here, `showFoo` is a boolean which controls whether or not to display the `<Foo />` element. If `showFoo` is true, then this evaluates to `{<Foo />}`. If `showFoo` is false, then this evaluates to `{false}`, which doesn’t display anything.

 Now suppose that instead of a boolean, we have a numerical value representing, say, the number of comments on a post. We want to display a count of the comments, unless there are no comments. We might naively try to do something similar to the boolean case:

 
```
{count && <>[{count} comments]</>}

```
 If `count` is, say, `5`, then this displays “[5 comments]”. However, if `count` is `0`, then this displays “0” instead of displaying nothing. (This problem is unique to `number` because `0` and `NaN` are the only falsy values which React renders with a visible result.) This could be subtly dangerous: if this immediately follows another numerical value, it might appear to the user that we have multiplied that value by 10! Instead, we should do a proper conditional check:

 
```
{count ? <>[{count} comments]</> : null}

```
 ### 
`unclear-type`

 Triggers when you use `any`, `Object`, or `Function` as type annotations. These types are unsafe.

 ### 
`unnecessary-invariant`

 Triggers when you use `invariant` to check a condition which we know must be truthy based on the available type information. This is quite conservative: for example, if all we know about the condition is that it is a `boolean`, then the lint will not fire even if the condition must be `true` at runtime.

 Note that this lint does not trigger when we know a condition is always `false`. It is a common idiom to use `invariant()` or `invariant(false, ...)` to throw in code that should be unreachable.

 ### 
`unnecessary-optional-chain`

 Triggers when you use `?.` where it isn’t needed. This comes in two main flavors. The first is when the left-hand-side cannot be nullish:

 
```
type Foo = {
  bar: number
}

declare var foo: Foo;
foo?.bar; // Lint: unnecessary-optional-chain

```
 The second is when the left-hand-side could be nullish, but the short-circuiting behavior of `?.` is sufficient to handle it anyway:

 
```
type Foo = {
  bar: {
    baz: number
  }
}

declare var foo: ?Foo;
foo?.bar?.baz; // Lint: unnecessary-optional-chain

```
 In the second example, the first use of `?.` is valid, since `foo` is potentially nullish, but the second use of `?.` is unnecessary. The left-hand-side of the second `?.` (`foo?.bar`) can only be nullish as a result of `foo` being nullish, and when `foo` is nullish, short-circuiting lets us avoid the second `?.` altogether!

 
```
foo?.bar.baz;

```
 This makes it clear to the reader that `bar` is not a potentially nullish property.

 ### 
`unsafe-getters-setters`

 Triggers when you use getters or setters. Getters and setters can have side effects and are unsafe.

 For example:

 
```
const o = {
  get a() { return 4; }, // Error: unsafe-getters-setters
  set b(x: number) { this.c = x; }, // Error: unsafe-getters-setters
  c: 10,
};

```
 ### 
`untyped-import`

 Triggers when you import from an untyped file. Importing from an untyped file results in those imports being typed as `any`, which is unsafe.

 ### 
`untyped-type-import`

 Triggers when you import a type from an untyped file. Importing a type from an untyped file results in an `any` alias, which is typically not the intended behavior. Enabling this lint brings extra attention to this case and can help improve Flow coverage of typed files by limiting the spread of implicit `any` types.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/linting/rule-reference>

Maybe Types
===========

 It’s common for JavaScript code to introduce “optional” values so that you have the option of leaving out the value or passing `null` instead.

 Using Flow you can use Maybe types for these values. Maybe types work with any other type by simply prefixing it with a question mark `?` such as `?number` as a sort of modifier.

 Maybe types accept the provided type as well as `null` or `undefined`. So `?number` would mean `number`, `null`, or `undefined`.

 
```
// @flow
function acceptsMaybeNumber(value: ?number) {
  // ...
}

acceptsMaybeNumber(42);        // Works!
acceptsMaybeNumber();          // Works!
acceptsMaybeNumber(undefined); // Works!
acceptsMaybeNumber(null);      // Works!
acceptsMaybeNumber("42");      // Error!

```
 In the case of objects, a **missing** property is not the same thing as an explicitly `undefined` property.

 
```
// @flow
function acceptsMaybeProp({ value }: { value: ?number }) {
  // ...
}

acceptsMaybeProp({ value: undefined }); // Works!
acceptsMaybeProp({});                   // Error!

```
 If you want to allow missing properties, use [optional property](../objects#toc-optional-object-type-properties) syntax, where the `?` is placed *before* the colon. It is also possible to combine both syntaxes for an optional maybe type, for example `{ value?: ?number }`.

 Refining Maybe types
--------------------

 Imagine we have the type `?number`, if we want to use that value as a `number` we’ll need to first check that it is not `null` or `undefined`.

 
```
// @flow
function acceptsMaybeNumber(value: ?number) {
  if (value !== null && value !== undefined) {
    return value * 2;
  }
}

```
 You can simplify the two checks against `null` and `undefined` using a single `!= null` check which will do both.

 
```
// @flow
function acceptsMaybeNumber(value: ?number) {
  if (value != null) {
    return value * 2;
  }
}

```
 You could also flip it around, and check to make sure that the value has a type of `number` before using it.

 
```
// @flow
function acceptsMaybeNumber(value: ?number) {
  if (typeof value === 'number') {
    return value * 2;
  }
}

```
 However, type refinements can be lost. For instance, calling a function after refining the type of an object’s property will invalidate this refinement. Consult the [Refinement Invalidations](https://flow.org/en/lang/refinements/#toc-refinement-invalidations) docs for more details, to understand why Flow works this way, and how you can avoid this common pitfall.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/maybe>

Variable Types
==============

 When you are declaring a new variable, you may optionally declare its type.

 JavaScript has three ways of declaring local variables:

 * `var` - declares a variable, optionally assigning a value. ([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var))
* `let` - declares a block-scoped variable, optionally assigning a value. ([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let))
* `const` - declares a block-scoped variable, assigning a value that cannot be re-assigned. ([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const))

 In Flow these fall into two groups:

 * `let` and `var` - variables that **can** be reassigned.
* `const` - variables that **cannot** be reassigned.

 
```
var varVariable = 1;
let letVariable = 1;
const constVariable = 1;

varVariable = 2;   // Works!
letVariable = 2;   // Works!
// $ExpectError
constVariable = 2; // Error!

```
 
`const`
--------

 Since a `const` variable cannot be re-assigned at a later time it is fairly simple.

 Flow can either infer the type from the value you are assigning to it or you can provide it with a type.

 
```
// @flow
const foo /* : number */ = 1;
const bar: number = 2;

```
 
`var` and `let`
----------------

 Since `var` and `let` can be re-assigned, there’s a few more rules you’ll need to know about.

 Similar to `const`, Flow can either infer the type from the value you are assigning to it or you can provide it with a type:

 
```
// @flow
var fooVar /* : number */ = 1;
let fooLet /* : number */ = 1;
var barVar: number = 2;
let barLet: number = 2;

```
 When you provide a type, you will be able to re-assign the value, but it must always be of a compatible type.

 
```
// @flow
let foo: number = 1;
foo = 2;   // Works!
// $ExpectError
foo = "3"; // Error!

```
 When you do not provide a type, the inferred type will do one of two things if you re-assign it.

 Reassigning variables
---------------------

 By default when you re-assign a variable, Flow will give it the type of all possible assignments.

 
```
let foo = 42;

if (Math.random()) foo = true;
if (Math.random()) foo = "hello";

let isOneOf: number | boolean | string = foo; // Works!

```
 Sometimes Flow is able to figure out (with certainty) the type of a variable after re-assignment. In that case, Flow will give it the known type.

 
```
// @flow
let foo = 42;
let isNumber: number = foo; // Works!

foo = true;
let isBoolean: boolean = foo; // Works!

foo = "hello";
let isString: string = foo; // Works!

```
 If statements, functions, and other conditionally run code can all prevent Flow from being able to figure out precisely what a type will be.

 
```
// @flow
let foo = 42;

function mutate() {
  foo = true;
  foo = "hello";
}

mutate();

// $ExpectError
let isString: string = foo; // Error!

```
 As Flow gets smarter and smarter, there should be fewer instances of these scenarios.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/variables>

Opaque Type Aliases
===================

 Opaque type aliases are type aliases that do not allow access to their underlying type outside of the file in which they are defined.

 
```
opaque type ID = string;

```
 Opaque type aliases, like regular type aliases, may be used anywhere a type can be used.

 
```
// @flow
opaque type ID = string;

function identity(x: ID): ID {
  return x;
}
export type {ID};

```
 Opaque Type Alias Syntax
------------------------

 Opaque type aliases are created using the words `opaque type` followed by its name, an equals sign `=`, and a type definition.

 
```
opaque type Alias = Type;

```
 You can optionally add a subtyping constraint to an opaque type alias by adding a colon `:` and a type after the name.

 
```
opaque type Alias: SuperType = Type;

```
 Any type can appear as the super type or type of an opaque type alias.

 
```
opaque type StringAlias = string;
opaque type ObjectAlias = {
  property: string,
  method(): number,
};
opaque type UnionAlias = 1 | 2 | 3;
opaque type AliasAlias: ObjectAlias = ObjectAlias;
opaque type VeryOpaque: AliasAlias = ObjectAlias;

```
 Opaque Type Alias Type Checking
-------------------------------

 ### Within the Defining File

 When in the same file the alias is defined, opaque type aliases behave exactly as regular [type aliases](../aliases) do.

 
```
//@flow
opaque type NumberAlias = number;

(0: NumberAlias);

function add(x: NumberAlias, y: NumberAlias): NumberAlias {
    return x + y;
}
function toNumberAlias(x: number): NumberAlias { return x; }
function toNumber(x: NumberAlias): number { return x; }

```
 ### Outside the Defining File

 When importing an opaque type alias, it behaves like a [nominal type](https://flow.org/en/lang/nominal-structural/#toc-nominal-typing), hiding its underlying type.

 **`exports.js`**

 
```
export opaque type NumberAlias = number;

```
 **`imports.js`**

 
```
import type {NumberAlias} from './exports';

(0: NumberAlias) // Error: 0 is not a NumberAlias!

function convert(x: NumberAlias): number {
  return x; // Error: x is not a number!
}

```
 ### Subtyping Constraints

 When you add a subtyping constraint to an opaque type alias, we allow the opaque type to be used as the super type when outside of the defining file.

 **`exports.js`**

 
```
export opaque type ID: string = string;

```
 **`imports.js`**

 
```
import type {ID} from './exports';

function formatID(x: ID): string {
    return "ID: " + x; // Ok! IDs are strings.
}

function toID(x: string): ID {
    return x; // Error: strings are not IDs.
}

```
 When you create an opaque type alias with a subtyping constraint, the type in the type position must be a subtype of the type in the super type position.

 
```
//@flow
opaque type Bad: string = number; // Error: number is not a subtype of string
opaque type Good: {x: string} = {x: string, y: number};

```
 ### Generics

 Opaque type aliases can also have their own [generics](../generics), and they work exactly as generics do in regular [type aliases](../aliases#toc-type-alias-generics)

 
```
// @flow
opaque type MyObject<A, B, C>: { foo: A, bar: B } = {
  foo: A,
  bar: B,
  baz: C,
};

var val: MyObject<number, boolean, string> = {
  foo: 1,
  bar: true,
  baz: 'three',
};

```
 ### Library Definitions

 You can also declare opaque type aliases in [libdefs](../libdefs). There, you omit the underlying type, but may still optionally include a super type.

 
```
declare opaque type Foo;
declare opaque type PositiveNumber: number;

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/opaque-types>

Type Aliases
============

 When you have complicated types that you want to reuse in multiple places, you can alias them in Flow using a **type alias**.

 
```
// @flow
type MyObject = {
  foo: number,
  bar: boolean,
  baz: string,
};

```
 These type aliases can be used anywhere a type can be used.

 
```
// @flow
type MyObject = {
  // ...
};

var val: MyObject = { /* ... */ };
function method(val: MyObject) { /* ... */ }
class Foo { constructor(val: MyObject) { /* ... */ } }

```
 Type Alias Syntax
-----------------

 Type aliases are created using the keyword `type` followed by its name, an equals sign `=`, and a type definition.

 
```
type Alias = Type;

```
 Any type can appear inside a type alias.

 
```
type NumberAlias = number;
type ObjectAlias = {
  property: string,
  method(): number,
};
type UnionAlias = 1 | 2 | 3;
type AliasAlias = ObjectAlias;

```
 ### Type Alias Generics

 Type aliases can also have their own [generics](../generics).

 
```
type MyObject<A, B, C> = {
  property: A,
  method(val: B): C,
};

```
 Type alias generics are [parameterized](../generics#toc-parameterized-generics). When you use a type alias you need to pass parameters for each of its generics.

 
```
// @flow
type MyObject<A, B, C> = {
  foo: A,
  bar: B,
  baz: C,
};

var val: MyObject<number, boolean, string> = {
  foo: 1,
  bar: true,
  baz: 'three',
};

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/aliases>

Interface Types
===============

 Classes in Flow are nominally typed. This means that when you have two separate classes you cannot use one in place of the other even when they have the same exact properties and methods.

 
```
// @flow
class Foo {
  serialize() { return '[Foo]'; }
}

class Bar {
  serialize() { return '[Bar]'; }
}

// $ExpectError
const foo: Foo = new Bar(); // Error!

```
 Instead, you can use `interface` in order to declare the structure of the class that you are expecting.

 
```
// @flow
interface Serializable {
  serialize(): string;
}

class Foo {
  serialize() { return '[Foo]'; }
}

class Bar {
  serialize() { return '[Bar]'; }
}

const foo: Serializable = new Foo(); // Works!
const bar: Serializable = new Bar(); // Works!

```
 You can also declare an anonymous interface:

 
```
// @flow
class Foo {
  a : number
}

(new Foo() : interface { a : number });

```
 You can also use `implements` to tell Flow that you want the class to match an interface. This prevents you from making incompatible changes when editing the class.

 
```
// @flow
interface Serializable {
  serialize(): string;
}

class Foo implements Serializable {
  serialize() { return '[Foo]'; } // Works!
}

class Bar implements Serializable {
  // $ExpectError
  serialize() { return 42; } // Error!
}

```
 You can also use `implements` with multiple interfaces.

 
```
class Foo implements Bar, Baz {
  // ...
}

```
 Interface Syntax
----------------

 Interfaces are created using the keyword `interface` followed by its name and a block which contains the body of the type definition.

 
```
interface MyInterface {
  // ...
}

```
 The syntax of the block matches the syntax of object types and has all of the same features.

 #### Interface Methods

 You can add methods to interfaces following the same syntax as class methods. Any `this` parameters you provide are also subject to the same restrictions as class methods.

 
```
interface MyInterface {
  method(value: string): number;
}

```
 Also like [class methods](../classes#toc-class-methods), interface methods must also remain bound to the interface on which they were defined.

 #### Interface Properties

 You can add properties to interfaces following the same syntax as class properties.

 
```
interface MyInterface {
  property: string;
}

```
 Interface properties can be optional as well.

 
```
interface MyInterface {
  property?: string;
}

```
 #### Interfaces as maps

 You can create [“indexer properties”](../objects#toc-objects-as-maps) the same way as with objects.

 
```
interface MyInterface {
  [key: string]: number;
}

```
 ### Interface Generics

 Interfaces can also have their own [generics](../generics).

 
```
interface MyInterface<A, B, C> {
  property: A;
  method(val: B): C;
}

```
 Interface generics are [parameterized](../generics#toc-parameterized-generics). When you use an interface you need to pass parameters for each of its generics.

 
```
// @flow
interface MyInterface<A, B, C> {
  foo: A;
  bar: B;
  baz: C;
}

var val: MyInterface<number, boolean, string> = {
  foo: 1,
  bar: true,
  baz: 'three',
};

```
 Interface property variance (read-only and write-only)
------------------------------------------------------

 Interface properties are [invariant](https://flow.org/en/lang/variance/) by default. But you can add modifiers to make them covariant (read-only) or contravariant (write-only).

 
```
interface MyInterface {
  +covariant: number;     // read-only
  -contravariant: number; // write-only
}

```
 ### Covariant (read-only) properties on interfaces

 You can make a property covariant by adding a plus symbol `+` in front of the property name.

 
```
interface MyInterface {
  +readOnly: number | string;
}

```
 This allows you to pass a more specific type in place of that property.

 
```
// @flow
interface Invariant {  property: number | string }
interface Covariant { +readOnly: number | string }

var x : { property : number } = { property : 42 };
var y : { readOnly : number } = { readOnly : 42 };

var value1: Invariant = x; // Error!
var value2: Covariant = y; // Works

```
 Because of how covariance works, covariant properties also become read-only when used. Which can be useful over normal properties.

 
```
// @flow
interface Invariant {  property: number | string }
interface Covariant { +readOnly: number | string }

function method1(value: Invariant) {
  value.property;        // Works!
  value.property = 3.14; // Works!
}

function method2(value: Covariant) {
  value.readOnly;        // Works!
  // $ExpectError
  value.readOnly = 3.14; // Error!
}

```
 ### Contravariant (write-only) properties on interfaces

 You can make a property contravariant by adding a minus symbol - in front of the property name.

 
```
interface InterfaceName {
  -writeOnly: number;
}

```
 This allows you to pass a less specific type in place of that property.

 
```
// @flow
interface Invariant     {  property: number }
interface Contravariant { -writeOnly: number }

var numberOrString = Math.random() > 0.5 ? 42 : 'forty-two';

// $ExpectError
var value1: Invariant     = { property: numberOrString };  // Error!
var value2: Contravariant = { writeOnly: numberOrString }; // Works!

```
 Because of how contravariance works, contravariant properties also become write-only when used. Which can be useful over normal properties.

 
```
interface Invariant     {   property: number }
interface Contravariant { -writeOnly: number }

function method1(value: Invariant) {
  value.property;        // Works!
  value.property = 3.14; // Works!
}

function method2(value: Contravariant) {
  // $ExpectError
  value.writeOnly;        // Error!
  value.writeOnly = 3.14; // Works!
}

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/interfaces>

Function Types
==============

 Functions have two places where types are applied: Parameters (input) and the return value (output).

 
```
// @flow
function concat(a: string, b: string): string {
  return a + b;
}

concat("foo", "bar"); // Works!
// $ExpectError
concat(true, false);  // Error!

```
 Using inference, these types are often optional:

 
```
// @flow
function concat(a, b) {
  return a + b;
}

concat("foo", "bar"); // Works!
// $ExpectError
concat(true, false);  // Error!

```
 Sometimes Flow’s inference will create types that are more permissive than you want them to be.

 
```
// @flow
function concat(a, b) {
  return a + b;
}

concat("foo", "bar"); // Works!
concat(1, 2);         // Works!

```
 For that reason (and others), it’s useful to write types for important functions.

 Syntax of functions
-------------------

 There are three forms of functions that each have their own slightly different syntax.

 ### Function Declarations

 Here you can see the syntax for function declarations with and without types added.

 
```
function method(str, bool, ...nums) {
  // ...
}

function method(str: string, bool?: boolean, ...nums: Array<number>): void {
  // ...
}

```
 ### Arrow Functions

 Here you can see the syntax for arrow functions with and without types added.

 
```
let method = (str, bool, ...nums) => {
  // ...
};

let method = (str: string, bool?: boolean, ...nums: Array<number>): void => {
  // ...
};

```
 ### Function Types

 Here you can see the syntax for writing types that are functions.

 
```
(str: string, bool?: boolean, ...nums: Array<number>) => void

```
 You may also optionally leave out the parameter names.

 
```
(string, boolean | void, Array<number>) => void

```
 You might use these functions types for something like a callback.

 
```
function method(callback: (error: Error | null, value: string | null) => void) {
  // ...
}

```
 Function Parameters
-------------------

 Function parameters can have types by adding a colon `:` followed by the type after the name of the parameter.

 
```
function method(param1: string, param2: boolean) {
  // ...
}

```
 Optional Parameters
-------------------

 You can also have optional parameters by adding a question mark `?` after the name of the parameter and before the colon `:`.

 
```
function method(optionalValue?: string) {
  // ...
}

```
 Optional parameters will accept missing, `undefined`, or matching types. But they will not accept `null`.

 
```
// @flow
function method(optionalValue?: string) {
  // ...
}

method();          // Works.
method(undefined); // Works.
method("string");  // Works.
// $ExpectError
method(null);      // Error!

```
 ### Rest Parameters

 JavaScript also supports having rest parameters or parameters that collect an array of arguments at the end of a list of parameters. These have an ellipsis `...` before them.

 You can also add type annotations for rest parameters using the same syntax but with an `Array`.

 
```
function method(...args: Array<number>) {
  // ...
}

```
 You can pass as many arguments as you want into a rest parameter.

 
```
// @flow
function method(...args: Array<number>) {
  // ...
}

method();        // Works.
method(1);       // Works.
method(1, 2);    // Works.
method(1, 2, 3); // Works.

```
 
>  Note: If you add a type annotation to a rest parameter, it must always explicitly be an `Array` type.
> 
>  

 ### Function Returns

 Function returns can also add a type using a colon `:` followed by the type after the list of parameters.

 
```
function method(): number {
  // ...
}

```
 Return types ensure that every branch of your function returns the same type. This prevents you from accidentally not returning a value under certain conditions.

 
```
// @flow
// $ExpectError
function method(): boolean {
  if (Math.random() > 0.5) {
    return true;
  }
}

```
 Async functions implicitly return a promise, so the return type must always be a `Promise`.

 
```
// @flow
async function method(): Promise<number> {
  return 123;
}

```
 ### Function `this`

 Every function in JavaScript can be called with a special context named `this`. You can call a function with any context that you want. Flow allows you to annotate the type for this context by adding a special parameter at the start of the function’s parameter list:

 
```
// @flow
function method<T>(this: { x: T }) : T {
  return this.x;
}

var num: number = method.call({x : 42});
var str: string = method.call({x : 42}); // error

```
 This parameter has no effect at runtime, and is erased along with types when Flow is transformed into JavaScript. When present, `this` parameters must always appear at the very beginning of the function’s parameter list, and must have an annotation. Additionally, [arrow functions](../types#toc-arrow-functions) may not have a `this` parameter annotation, as these functions bind their `this` parameter at the definition site, rather than the call site.

 If an explicit `this` parameter is not provided, Flow will attempt to infer one based on usage. If `this` is not mentioned in the body of the function, Flow will infer `mixed` for its `this` parameter.

 ### Predicate Functions

 Sometimes you will want to move the condition from an `if` statement into a function:

 
```
function concat(a: ?string, b: ?string): string {
  if (a && b) {
    return a + b;
  }
  return '';
}

```
 However, Flow will flag an error in the code below:

 
```
function truthy(a, b): boolean {
  return a && b;
}

function concat(a: ?string, b: ?string): string {
  if (truthy(a, b)) {
    // $ExpectError
    return a + b;
  }
  return '';
}

```
 You can fix this by making `truthy` a *predicate function*, by using the `%checks` annotation like so:

 
```
function truthy(a, b): boolean %checks {
  return !!a && !!b;
}

function concat(a: ?string, b: ?string): string {
  if (truthy(a, b)) {
    return a + b;
  }
  return '';
}

```
 #### Limitations of predicate functions

 The body of these predicate functions need to be expressions (i.e. local variable declarations are not supported). But it’s possible to call other predicate functions inside a predicate function. For example:

 
```
function isString(y): %checks {
  return typeof y === "string";
}

function isNumber(y): %checks {
  return typeof y === "number";
}

function isNumberOrString(y): %checks {
  return isString(y) || isNumber(y);
}

function foo(x): string | number {
  if (isNumberOrString(x)) {
    return x + x;
  } else {
    return x.length; // no error, because Flow infers that x can only be an array
  }
}

foo('a');
foo(5);
foo([]);

```
 Another limitation is on the range of predicates that can be encoded. The refinements that are supported in a predicate function must refer directly to the value that is passed in as an argument to the respective call.

 For example, consider the *inlined* refinement

 
```
declare var obj: { n?: number };

if (obj.n) {
  const n: number = obj.n;
}

```
 Here, Flow will let you refine `obj.n` from `?number` to `number`. Note that the refinement here is on the property `n` of `obj`, rather than `obj` itself.

 If you tried to create a *predicate* function

 
```
function bar(a): %checks {
  return a.n;
}

```
 to encode the same condition, then the following refinement would fail

 
```
if (bar(obj)) {
  // $ExpectError
  const n: number = obj.n;
}

```
 This is because the only refinements supported through `bar` would be on `obj` itself.

 ### Callable Objects

 Callable objects can be typed, for example:

 
```
type CallableObj = {
  (number, number): number,
  bar: string
};

function add(x, y) {
  return x + y;
}

// $ExpectError
(add: CallableObj);

add.bar = "hello world";

(add: CallableObj);

```
 ### 
`Function` Type

 
>  NOTE: For new code prefer `any` or `(...args: Array<any>) => any`. `Function` has become an alias to `any` and will be deprecated and removed in a future version of Flow.
> 
>  

 Sometimes it is useful to write types that accept arbitrary functions, for those you should write `() => mixed` like this:

 
```
function method(func: () => mixed) {
  // ...
}

```
 However, if you need to opt-out of the type checker, and don’t want to go all the way to `any`, you can instead use `(...args: Array<any>) => any`. (Note that [`any`](../any) is unsafe and should be avoided). For historical reasons, the `Function` keyword is still available.

 For example, the following code will not report any errors:

 
```
function method(func: (...args: Array<any>) => any) {
  func(1, 2);     // Works.
  func("1", "2"); // Works.
  func({}, []);   // Works.
}

method(function(a: number, b: number) {
  // ...
});

```
 Neither will this:

 
```
function method(obj: Function) {
  obj = 10;
}

method(function(a: number, b: number) {
  // ...
});

```
 
>  ***You should follow [all the same rules](../any) as `any` when using `Function`.***
> 
>  



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/functions>

Module Types
============

 Importing and exporting types
-----------------------------

 It is often useful to share types in between modules (files). In Flow, you can export type aliases, interfaces, and classes from one file and import them in another.

 **`exports.js`**

 
```
// @flow
export default class Foo {};
export type MyObject = { /* ... */ };
export interface MyInterface { /* ... */ };

```
 **`imports.js`**

 
```
// @flow
import type Foo, {MyObject, MyInterface} from './exports';

```
 
>  ***Don’t forget to mention `@flow` on top of file, otherwise flow won’t report errors***.
> 
>  

 Importing and exporting values
------------------------------

 Flow also supports importing the type of values exported by other modules using [`typeof`](../typeof).

 **`exports.js`**

 
```
// @flow
const myNumber = 42;
export default myNumber;
export class MyClass {
  // ...
}

```
 **`imports.js`**

 
```
// @flow
import typeof myNumber from './exports';
import typeof {MyClass} from './exports';

```
 Just like other type imports, this code will be stripped away by a compiler and will not add a dependency on the other module.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/modules>

Object Types
============

 Objects can be used in many different ways in JavaScript. There are a number of different ways to type them in order to support all the different use cases.

 In Flow, there are two different kinds of object types: exact object types and inexact object types.

 In general, we recommend using [exact object types](#toc-exact-object-types) whenever possible. Exact object types are more precise and interact better with other type system features, like spreads.

 Object type syntax
------------------

 Object types try to match the syntax for objects in JavaScript as much as possible. Using curly braces `{}` and name-value pairs using a colon `:` split by commas `,`.

 
```
// @flow
var obj1: { foo: boolean } = { foo: true };
var obj2: {
  foo: number,
  bar: boolean,
  baz: string,
} = {
  foo: 1,
  bar: true,
  baz: 'three',
};

```
 
>  **Note:** Previously object types used semicolons `;` for splitting name-value pairs. While the syntax is still valid, you should use commas `,`.
> 
>  

 #### Optional object type properties

 In JavaScript, accessing a property that doesn’t exist evaluates to `undefined`. This is a common source of errors in JavaScript programs, so Flow turns these into type errors.

 
```
// @flow
var obj = { foo: "bar" };
// $ExpectError
obj.bar; // Error!

```
 If you have an object that sometimes does not have a property you can make it an *optional property* by adding a question mark `?` after the property name in the object type.

 
```
// @flow
var obj: { foo?: boolean } = {};

obj.foo = true;    // Works!
// $ExpectError
obj.foo = 'hello'; // Error!

```
 In addition to their set value type, these optional properties can either be `void` or omitted altogether. However, they cannot be `null`.

 
```
// @flow
function acceptsObject(value: { foo?: string }) {
  // ...
}

acceptsObject({ foo: "bar" });     // Works!
acceptsObject({ foo: undefined }); // Works!
// $ExpectError
acceptsObject({ foo: null });      // Error!
acceptsObject({});                 // Works!

```
 ### Object methods

 Method syntax in objects has the same runtime behavior as a function property. These two objects are equivalent at runtime:

 
```
// @flow
let a = {
  foo : function () { return 3; }
};
let b = {
  foo() { return 3; }
}

```
 However, despite their equivalent runtime behavior, Flow checks them slightly differently. In particular, object properties written with method syntax are read-only; Flow will not allow you to write a new value to them.

 
```
// @flow
let b = {
  foo() { return 3; }
}
b.foo = () => { return 2; } // Error!

```
 Additionally, object methods do not allow the use of `this` in their bodies, in order to guarantee simple behavior for their `this` parameters. Prefer to reference the object by name instead of using `this`.

 
```
// @flow
let a = {
  x : 3,
  foo() { return this.x; } // error!
}
let b = {
  x : 3,
  foo() { return b.x; } // works!
}

```
 Object type inference
---------------------

 Flow can infer the type of object literals in two different ways depending on how they are used.

 ### Sealed objects

 When you create an object with its properties, you create a *sealed* object type in Flow. These sealed objects will know all of the properties you declared them with and the types of their values.

 
```
// @flow
var obj = {
  foo: 1,
  bar: true,
  baz: 'three'
};

var foo: number  = obj.foo; // Works!
var bar: boolean = obj.bar; // Works!
// $ExpectError
var baz: null    = obj.baz; // Error!
var bat: string  = obj.bat; // Error!

```
 But when objects are sealed, Flow will not allow you to add new properties to them.

 
```
// @flow
var obj = {
  foo: 1
};

// $ExpectError
obj.bar = true;    // Error!
// $ExpectError
obj.baz = 'three'; // Error!

```
 The workaround here might be to turn your object into an *unsealed object*.

 ### Unsealed objects

 When you create an object without any properties, you create an *unsealed* object type in Flow. These unsealed objects will not know all of their properties and will allow you to add new ones.

 
```
// @flow
var obj = {};

obj.foo = 1;       // Works!
obj.bar = true;    // Works!
obj.baz = 'three'; // Works!

```
 The inferred type of the property becomes what you set it to.

 
```
// @flow
var obj = {};
obj.foo = 42;
var num: number = obj.foo;

```
 ##### Reassigning unsealed object properties

 Similar to [`var` and `let` variables](../variables#toc-reassigning-variables) if you reassign a property of an unsealed object, by default Flow will give it the type of all possible assignments.

 
```
// @flow
var obj = {};

if (Math.random()) obj.prop = true;
else obj.prop = "hello";

// $ExpectError
var val1: boolean = obj.prop; // Error!
// $ExpectError
var val2: string  = obj.prop; // Error!
var val3: boolean | string = obj.prop; // Works!

```
 Sometimes Flow is able to figure out (with certainty) the type of a property after reassignment. In that case, Flow will give it the known type.

 
```
// @flow
var obj = {};

obj.prop = true;
obj.prop = "hello";

// $ExpectError
var val1: boolean = obj.prop; // Error!
var val2: string  = obj.prop; // Works!

```
 As Flow gets smarter and smarter, it will figure out the types of properties in more scenarios.

 ##### Unknown property lookup on unsealed objects is unsafe

 Unsealed objects allow new properties to be written at any time. Flow ensures that reads are compatible with writes, but does not ensure that writes happen before reads (in the order of execution).

 This means that reads from unsealed objects with no matching writes are never checked. This is an unsafe behavior of Flow which may be improved in the future.

 
```
var obj = {};

obj.foo = 1;
obj.bar = true;

var foo: number  = obj.foo; // Works!
var bar: boolean = obj.bar; // Works!
var baz: string  = obj.baz; // Works?

```
 Exact object types
------------------

 In Flow, it is considered safe to pass an object with extra properties where a normal object type is expected.

 
```
// @flow
function method(obj: { foo: string }) {
  // ...
}

method({
  foo: "test", // Works!
  bar: 42      // Works!
});

```
 
>  **Note:** This is because of [“width subtyping”](https://flow.org/en/lang/width-subtyping/).
> 
>  

 Sometimes it is useful to disable this behavior and only allow a specific set of properties. For this, Flow supports “exact” object types.

 
```
{| foo: string, bar: number |}

```
 Unlike regular object types, it is not valid to pass an object with “extra” properties to an exact object type.

 
```
// @flow
var foo: {| foo: string |} = { foo: "Hello", bar: "World!" }; // Error!

```
 Intersections of exact object types may not work as you expect. If you need to combine exact object types, use object type spread:

 
```
// @flow

type FooT = {| foo: string |};
type BarT = {| bar: number |};

type FooBarFailT = FooT & BarT;
type FooBarT = {| ...FooT, ...BarT |};

const fooBarFail: FooBarFailT = { foo: '123', bar: 12 }; // Error!
const fooBar: FooBarT = { foo: '123', bar: 12 }; // Works!

```
 Explicit inexact object types
-----------------------------

 In addition to the default `{}` syntax, you can explicitly indicate an inexact object by using an ellipsis at the end of your property list:

 
```
// @flow

type Inexact = {foo: number, ...};

```
 [Flow is planning to make object types exact by default](https://medium.com/flow-type/on-the-roadmap-exact-objects-by-default-16b72933c5cf). This is available via an [option in your flowconfig](https://flow.org/en/config/options/#toc-exact-by-default-boolean). You can also read our [upgrade guide](https://medium.com/flow-type/how-to-upgrade-to-exact-by-default-object-type-syntax-7aa44b4d08ab) for steps to enable this option in your own project.

 In a project using exact-by-default syntax, the explicit inexact object type syntax is the only way to express an inexact object type.

 Objects as maps
---------------

 Newer versions of the JavaScript standard include a `Map` class, but it is still very common to use objects as maps as well. In this use case, an object will likely have properties added to it and retrieved throughout its lifecycle. Furthermore, the property keys may not even be known statically, so writing out a type annotation would not be possible.

 For objects like these, Flow provides a special kind of property, called an “indexer property.” An indexer property allows reads and writes using any key that matches the indexer key type.

 
```
// @flow
var o: { [string]: number } = {};
o["foo"] = 0;
o["bar"] = 1;
var foo: number = o["foo"];

```
 An indexer can be optionally named, for documentation purposes:

 
```
// @flow
var obj: { [user_id: number]: string } = {};
obj[1] = "Julia";
obj[2] = "Camille";
obj[3] = "Justin";
obj[4] = "Mark";

```
 When an object type has an indexer property, property accesses are assumed to have the annotated type, even if the object does not have a value in that slot at runtime. It is the programmer’s responsibility to ensure the access is safe, as with arrays.

 
```
var obj: { [number]: string } = {};
obj[42].length; // No type error, but will throw at runtime

```
 Indexer properties can be mixed with named properties:

 
```
// @flow
var obj: {
  size: number,
  [id: number]: string
} = {
  size: 0
};

function add(id: number, name: string) {
  obj[id] = name;
  obj.size++;
}

```
 ### 
`Object` Type

 
>  NOTE: For new code, prefer `any` or `{ [key: string]: any}`. `Object` is an alias to [`any`](../any) and will be deprecated and removed in a future version of Flow.
> 
>  

 Sometimes it is useful to write types that accept arbitrary objects, for those you should write `{}` like this:

 
```
function method(obj: {}) {
  // ...
}

```
 However, if you need to opt-out of the type checker, and don’t want to go all the way to `any`, you could use `{ [key: string]: any}`. (Note that [`any`](../any) is unsafe and should be avoided). For historical reasons, the `Object` keyword is still available. In previous versions of Flow, `Object` was the same as `{ [key: string]: any}`.

 For example, the following code will not report any errors:

 
```
function method(obj: { [key: string]: any }) {
  obj.foo = 42;               // Works.
  let bar: boolean = obj.bar; // Works.
  obj.baz.bat.bam.bop;        // Works.
}

method({ baz: 3.14, bar: "hello" });

```
 Neither will this:

 
```
function method(obj: Object) {
  obj = 10;
}

method({ baz: 3.14, bar: "hello" });

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/objects>

Union Types
===========

 Sometimes it’s useful to create a type which is ***one of*** a set of other types. For example, you might want to write a function which accepts a set of primitive value types. For this Flow supports **union types**.

 
```
// @flow
function toStringPrimitives(value: number | boolean | string) {
  return String(value);
}

toStringPrimitives(1);       // Works!
toStringPrimitives(true);    // Works!
toStringPrimitives('three'); // Works!

// $ExpectError
toStringPrimitives({ prop: 'val' }); // Error!
// $ExpectError
toStringPrimitives([1, 2, 3, 4, 5]); // Error!

```
 Union type syntax
-----------------

 Union types are any number of types which are joined by a vertical bar `|`.

 
```
Type1 | Type2 | ... | TypeN

```
 You may also add a leading vertical bar which is useful when breaking union types onto multiple lines.

 
```
type Foo =
  | Type1
  | Type2
  | ...
  | TypeN

```
 Each of the members of a union type can be any type, even another union type.

 
```
type Numbers = 1 | 2;
type Colors = 'red' | 'blue'

type Fish = Numbers | Colors;

```
 If you have enabled [Flow Enums](https://flow.org/en/enums/), they may be an alternative to unions of primitive values.

 Union types requires one in, but all out
----------------------------------------

 When calling our function that accepts a union type we must pass in ***one of those types***. But inside of our function we are required to handle ***all of the possible types***.

 Let’s rewrite our function to handle each type individually.

 
```
// @flow
// $ExpectError
function toStringPrimitives(value: number | boolean | string): string { // Error!
  if (typeof value === 'number') {
    return String(value);
  } else if (typeof value === 'boolean') {
    return String(value);
  }
}

```
 You’ll notice that if we do not handle each possible type of our value, Flow will give us an error.

 Unions & Refinements
--------------------

 When you have a value which is a union type it’s often useful to break it apart and handle each individual type separately. With union types in Flow you can “refine” the value down to a single type.

 For example, if we have a value with a union type that is a `number`, a `boolean`, or a `string`, we can treat the number case separately by using JavaScript’s `typeof` operator.

 
```
// @flow
function toStringPrimitives(value: number | boolean | string) {
  if (typeof value === 'number') {
    return value.toLocaleString([], { maximumSignificantDigits: 3 }); // Works!
  }
  // ...
}

```
 By checking the typeof our value and testing to see if it is a number, Flow knows that inside of that block it is only a number. We can then write code which treats our value as a number inside of that block.

 ### Disjoint Object Unions

 There’s a special type of union in Flow known as a “disjoint object union” which can be used in [refinements](https://flow.org/en/lang/refinements/). These disjoint object unions are made up of any number of object types which are each tagged by a single property.

 For example, imagine we have a function for handling a response from a server after we’ve sent it a request. When the request is successful, we’ll get back an object with a `type` property set to `'success'` and a `value` that we’ve updated.

 
```
{ type: 'success', value: 23 };

```
 When the request fails, we’ll get back an object with `type` set to `'error'` and an `error` property describing the error.

 
```
{ type: 'error', error: 'Bad request' };

```
 We can try to express both of these objects in a single object type. However, we’ll quickly run into issues where we know a property exists based on the `type` property but Flow does not.

 
```
// @flow
type Response = {
  type: 'success' | 'error',
  value?: number,
  error?: string
};

function handleResponse(response: Response) {
  if (response.type === 'success') {
    // $ExpectError
    const value: number = response.value; // Error!
  } else {
    // $ExpectError
    const error: string = response.error; // Error!
  }
}

```
 Trying to combine these two separate types into a single one will only cause us trouble.

 Instead, if we create a union type of both object types, Flow will be able to know which object we’re using based on the `type` property.

 
```
// @flow
type Response =
  | { type: 'success', value: 23 }
  | { type: 'error', error: string };

function handleResponse(response: Response) {
  if (response.type === 'success') {
    const value: number = response.value; // Works!
  } else {
    const error: string = response.error; // Works!
  }
}

```
 In order to use this pattern, there must be a key that is in every object in your union (in our example above, `type`), and every object must set a different [literal type](../literals) for that key (in our example, the string `'success'`, and the string `'error'`). You can use any kind of literal type, including numbers and booleans.

 ### Disjoint unions with exact types

 Disjoint unions require you to use a single property to distinguish each object type. You cannot distinguish two different objects by different properties.

 
```
// @flow
type Success = { success: true, value: boolean };
type Failed  = { error: true, message: string };

function handleResponse(response:  Success | Failed) {
  if (response.success) {
    // $ExpectError
    var value: boolean = response.value; // Error!
  }
}

```
 This is because in Flow it is okay to pass an object value with more properties than the object type expects (because of width subtyping).

 
```
// @flow
type Success = { success: true, value: boolean };
type Failed  = { error: true, message: string };

function handleResponse(response:  Success | Failed) {
  // ...
}

handleResponse({
  success: true,
  error: true,
  value: true,
  message: 'hi'
});

```
 Unless the objects somehow conflict with one another there is no way to distinguish them.

 However, to get around this you could use **exact object types**.

 
```
// @flow
type Success = {| success: true, value: boolean |};
type Failed  = {| error: true, message: string |};

type Response = Success | Failed;

function handleResponse(response: Response) {
  if (response.success) {
    var value: boolean = response.value;
  } else {
    var message: string = response.message;
  }
}

```
 With exact object types, we cannot have additional properties, so the objects conflict with one another and we are able to distinguish which is which.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/unions>

Sublime Text
============

 Flow For Sublime Text 2 and 3
-----------------------------

 [Sublime Text](https://www.sublimetext.com/) can be integrated with Flow by using [Package Control](https://packagecontrol.io)

 * Install the Package Control plugin if you don’t have it
* Press Ctrl+Shift+P to bring up the Command Palette (or use Tools > Command Palette menu)
* Select Package Control: Install Package
* Type ‘Flow’ to find ‘Flow for Sublime Text 2 and 3’
* Select ‘Flow for Sublime Text 2 and 3’ to install

 SublimeLinter-flow
------------------

 You may also wish to install a popular SublimeLinter plugin for Flow like [SublimeLinter-flow](https://packagecontrol.io/packages/SublimeLinter-flow).



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/editors/sublime-text>

Visual Studio Code
==================

 ![Screenshot of Flow Language Support](https://flow.org/static/flow_for_vscode.gif)

 Support for Flow in [Visual Studio Code](https://code.visualstudio.com/) is provided by the [Flow Language Support](https://marketplace.visualstudio.com/items?itemName=flowtype.flow-for-vscode) extension. It provides all the functionality you would expect:

 * IntelliSense (Autocomplete)
* Go to Definition / Peek Definition
* Diagnostics (Errors, Warnings)
* Hover type information
* Toggleable code coverage reports

 Installation
------------

 Search for “Flow Language Support” in the VS Code extensions panel or install through the [Marketplace](https://marketplace.visualstudio.com/items?itemName=flowtype.flow-for-vscode).



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/editors/vscode>

Generic Types
=============

 Generics (sometimes referred to as polymorphic types) are a way of abstracting a type away.

 Imagine writing the following `identity` function which returns whatever value was passed.

 
```
function identity(value) {
  return value;
}

```
 We would have a lot of trouble trying to write specific types for this function since it could be anything.

 
```
function identity(value: string): string {
  return value;
}

```
 Instead we can create a generic (or polymorphic type) in our function and use it in place of other types.

 
```
function identity<T>(value: T): T {
  return value;
}

```
 Generics can be used within functions, function types, classes, type aliases, and interfaces.

 
>  **Warning:** Flow does not infer generic types. If you want something to have a generic type, **annotate it**. Otherwise, Flow may infer a type that is less polymorphic than you expect.
> 
>  

 In the following example, we forget to properly annotate `identity` with a generic type, so we run into trouble when we try to assign it to `func`. On the other hand, `genericIdentity` is properly typed, and we are able to use it as expected.

 
```
// @flow

type IdentityWrapper = {
  func<T>(T): T
}

function identity(value) {
  return value;
}

function genericIdentity<T>(value: T): T {
  return value;
}

// $ExpectError
const bad: IdentityWrapper = { func: identity }; // Error!
const good: IdentityWrapper = { func: genericIdentity }; // Works!

```
 ### Syntax of generics

 There are a number of different places where generic types appear in syntax.

 ##### Functions with generics

 Functions can create generics by adding the type parameter list `<T>` before the function parameter list.

 You can use generics in the same places you’d add any other type in a function (parameter or return types).

 
```
function method<T>(param: T): T {
  // ...
}

function<T>(param: T): T {
  // ...
}

```
 ##### Function types with generics

 Function types can create generics in the same way as normal functions, by adding the type parameter list `<T>` before the function type parameter list.

 You can use generics in the same places you’d add any other type in a function type (parameter or return types).

 
```
<T>(param: T) => T

```
 Which then gets used as its own type.

 
```
function method(func: <T>(param: T) => T) {
  // ...
}

```
 ##### Classes with generics

 Classes can create generics by placing the type parameter list before the body of the class.

 
```
class Item<T> {
  // ...
}

```
 You can use generics in the same places you’d add any other type in a class (property types and method parameter/return types).

 
```
class Item<T> {
  prop: T;

  constructor(param: T) {
    this.prop = param;
  }

  method(): T {
    return this.prop;
  }
}

```
 ##### Type aliases with generics

 
```
type Item<T> = {
  foo: T,
  bar: T,
};

```
 ##### Interfaces with generics

 
```
interface Item<T> {
  foo: T,
  bar: T,
}

```
 ##### Supplying Type Arguments to Callables

 You can give callable entities type arguments for their generics directly in the call:

 
```
//@flow
function doSomething<T>(param: T): T {
  // ...
  return param;
}

doSomething<number>(3);

```
 You can also give generic classes type arguments directly in the `new` expression:

 
```
//@flow
class GenericClass<T> {}
const c = new GenericClass<number>();

```
 If you only want to specify some of the type arguments, you can use `_` to let flow infer a type for you:

 
```
//@flow
class GenericClass<T, U, V>{}
const c = new GenericClass<_, number, _>()

```
 
>  **Warning:** For performance purposes, we always recommend you annotate with concrete arguments when you can. `_` is not unsafe, but it is slower than explicitly specifying the type arguments.
> 
>  

 Behavior of generics
--------------------

 #### Generics act like variables

 Generic types work a lot like variables or function parameters except that they are used for types. You can use them whenever they are in scope.

 
```
function constant<T>(value: T): () => T {
  return function(): T {
    return value;
  };
}

```
 #### Create as many generics as you need

 You can have as many of these generics as you need in the type parameter list, naming them whatever you want:

 
```
function identity<One, Two, Three>(one: One, two: Two, three: Three) {
  // ...
}

```
 #### Generics track values around

 When using a generic type for a value, Flow will track the value and make sure that you aren’t replacing it with something else.

 
```
// @flow
function identity<T>(value: T): T {
  // $ExpectError
  return "foo"; // Error!
}

function identity<T>(value: T): T {
  // $ExpectError
  value = "foo"; // Error!
  // $ExpectError
  return value;  // Error!
}

```
 Flow tracks the specific type of the value you pass through a generic, letting you use it later.

 
```
// @flow
function identity<T>(value: T): T {
  return value;
}

let one: 1 = identity(1);
let two: 2 = identity(2);
// $ExpectError
let three: 3 = identity(42);

```
 #### Adding types to generics

 Similar to `mixed`, generics have an “unknown” type. You’re not allowed to use a generic as if it were a specific type.

 
```
// @flow
function logFoo<T>(obj: T): T {
  // $ExpectError
  console.log(obj.foo); // Error!
  return obj;
}

```
 You could refine the type, but the generic will still allow any type to be passed in.

 
```
// @flow
function logFoo<T>(obj: T): T {
  if (obj && obj.foo) {
    console.log(obj.foo); // Works.
  }
  return obj;
}

logFoo({ foo: 'foo', bar: 'bar' });  // Works.
logFoo({ bar: 'bar' }); // Works. :(

```
 Instead, you could add a type to your generic like you would with a function parameter.

 
```
// @flow
function logFoo<T: { foo: string }>(obj: T): T {
  console.log(obj.foo); // Works!
  return obj;
}

logFoo({ foo: 'foo', bar: 'bar' });  // Works!
// $ExpectError
logFoo({ bar: 'bar' }); // Error!

```
 This way you can keep the behavior of generics while only allowing certain types to be used.

 
```
// @flow
function identity<T: number>(value: T): T {
  return value;
}

let one: 1 = identity(1);
let two: 2 = identity(2);
// $ExpectError
let three: "three" = identity("three");

```
 #### Generic types act as bounds

 
```
// @flow
function identity<T>(val: T): T {
  return val;
}

let foo: 'foo' = 'foo';           // Works!
let bar: 'bar' = identity('bar'); // Works!

```
 In Flow, most of the time when you pass one type into another you lose the original type. So that when you pass a specific type into a less specific one Flow “forgets” it was once something more specific.

 
```
// @flow
function identity(val: string): string {
  return val;
}

let foo: 'foo' = 'foo';           // Works!
// $ExpectError
let bar: 'bar' = identity('bar'); // Error!

```
 Generics allow you to hold onto the more specific type while adding a constraint. In this way types on generics act as “bounds”.

 
```
// @flow
function identity<T: string>(val: T): T {
  return val;
}

let foo: 'foo' = 'foo';           // Works!
let bar: 'bar' = identity('bar'); // Works!

```
 Note that when you have a value with a bound generic type, you can’t use it as if it were a more specific type.

 
```
// @flow
function identity<T: string>(val: T): T {
  let str: string = val; // Works!
  // $ExpectError
  let bar: 'bar'  = val; // Error!
  return val;
}

identity('bar');

```
 #### Parameterized generics

 Generics sometimes allow you to pass types in like arguments to a function. These are known as parameterized generics (or parametric polymorphism).

 For example, a type alias with a generic is parameterized. When you go to use it you will have to provide a type argument.

 
```
type Item<T> = {
  prop: T,
}

let item: Item<string> = {
  prop: "value"
};

```
 You can think of this like passing arguments to a function, only the return value is a type that you can use.

 Classes (when being used as a type), type aliases, and interfaces all require that you pass type arguments. Functions and function types do not have parameterized generics.

 ***Classes***

 
```
// @flow
class Item<T> {
  prop: T;
  constructor(param: T) {
    this.prop = param;
  }
}

let item1: Item<number> = new Item(42); // Works!
// $ExpectError
let item2: Item = new Item(42); // Error!

```
 ***Type Aliases***

 
```
// @flow
type Item<T> = {
  prop: T,
};

let item1: Item<number> = { prop: 42 }; // Works!
// $ExpectError
let item2: Item = { prop: 42 }; // Error!

```
 ***Interfaces***

 
```
// @flow
interface HasProp<T> {
  prop: T,
}

class Item {
  prop: string;
}

(Item.prototype: HasProp<string>); // Works!
// $ExpectError
(Item.prototype: HasProp); // Error!

```
 ##### Adding defaults to parameterized generics

 You can also provide defaults for parameterized generics just like parameters of a function.

 
```
type Item<T: number = 1> = {
  prop: T,
};

let foo: Item<> = { prop: 1 };
let bar: Item<2> = { prop: 2 };

```
 You must always include the brackets `<>` when using the type (just like parentheses for a function call).

 #### Variance Sigils

 You can also specify the subtyping behavior of a generic via variance sigils. By default, generics behave invariantly, but you may add a `+` to their declaration to make them behave covariantly, or a `-` to their declaration to make them behave contravariantly. See [our docs on variance](https://flow.org/en/lang/variance) for a more information on variance in Flow.

 Variance sigils allow you to be more specific about how you intend to use your generics, giving Flow the power to do more precise type checking. For example, you may want this relationship to hold:

 
```
//@flow
type GenericBox<+T> = T;

var x: GenericBox<number> = 3;
(x: GenericBox<number| string>);

```
 The example above could not be accomplished without the `+` variance sigil:

 
```
//@flow
type GenericBoxError<T> = T;

var x: GenericBoxError<number> = 3;
(x: GenericBoxError<number| string>); // number | string is not compatible with number.

```
 Note that if you annotate your generic with variance sigils then Flow will check to make sure those types only appear in positions that make sense for that variance sigil. For example, you cannot declare a generic type parameter to behave covariantly and use it in a contravariant position:

 
```
//@flow
type NotActuallyCovariant<+T> = (T) => void;

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/generics>

Intersection Types
==================

 Sometimes it is useful to create a type which is ***all of*** a set of other types. For example, you might want to write a function which accepts an object which is the combination of other object types. For this, Flow supports **intersection types**.

 
```
// @flow
type A = { a: number };
type B = { b: boolean };
type C = { c: string };

function method(value: A & B & C) {
  // ...
}

// $ExpectError
method({ a: 1 }); // Error!
// $ExpectError
method({ a: 1, b: true }); // Error!
method({ a: 1, b: true, c: 'three' }); // Works!

```
 Intersection type syntax
------------------------

 Intersection types are any number of types which are joined by an ampersand `&`.

 
```
Type1 & Type2 & ... & TypeN

```
 You may also add a leading ampersand which is useful when breaking intersection types onto multiple lines.

 
```
type Foo =
  & Type1
  & Type2
  & ...
  & TypeN

```
 Each of the members of a intersection type can be any type, even another intersection type.

 
```
type Foo = Type1 & Type2;
type Bar = Type3 & Type4;

type Baz = Foo & Bar;

```
 Intersection types require all in, but one out
----------------------------------------------

 Intersection types are the opposite of union types. When calling a function that accepts an intersection type, we must pass in ***all of those types***. But inside of our function we only have to treat it as ***any one of those types***.

 
```
// @flow
type A = { a: number };
type B = { b: boolean };
type C = { c: string };

function method(value: A & B & C) {
  var a: A = value;
  var b: B = value;
  var c: C = value;
}

```
 Even as we treat our value as just one of the types, we do not get an error because it satisfies all of them.

 Intersection of function types
------------------------------

 A common use of intersection types is to express functions that return different results based on the input we pass in. Suppose for example that we want to write the type of a function that

 * returns a string, when we pass in the value `"string"`,
* returns a number, when we pass in the value `"number"`, and
* returns any possible type (`mixed`), when we pass in any other string.

 The type of this function will be

 
```
type Fn =
  & ((x: "string") => string)
  & ((x: "number") => number)
  & ((x: string) => null);

```
 Each line in the above definition is called an *overload*, and we say that functions of type `Fn` are *overloaded*.

 Note the use of parentheses around the arrow types. These are necessary to override the precedence of the “arrow” constructor over the intersection.

 ### Calling an overloaded function

 Using the above definition we can declare a function `fn` that has the following behavior:

 
```
declare var fn: Fn;
var n: string = fn("string"); // okay
var n: number = fn("number"); // okay
var n: boolean = fn("boolean"); // error: null is incompatible with number

```
 Flow achieves this behavior by matching the type of the argument to the *first* overload with a compatible parameter type. Notice for example that the argument `"string"` matches both the first and the last overload. Flow will just pick the first one. If no overload matches, Flow will raise an error at the call site.

 ### Declaring overloaded functions

 An equivalent way to declare the same function `fn` would be by using consecutive “declare function” statements

 
```
declare function fn(x: "string"): string;
declare function fn(x: "number"): number;
declare function fn(x: string): null;

```
 A limitation in Flow is that it can’t *check* the body of a function against an intersection type. In other words, if we provided the following implementation for `fn` right after the above declarations

 
```
function fn(x) {
  if (x === "string") { return ""; }
  else if (x === "number") { return 0; }
  else { return null; }
}

```
 Flow silently accepts it (and uses `Fn` as the inferred type), but does not check the implementation against this signature. This makes this kind of declaration a better suited candidate for library definitions, where implementations are omitted.

 Intersections of object types
-----------------------------

 When you create an intersection of object types, you merge all of their properties together.

 For example, when you create an intersection of two objects with different sets of properties, it will result in an object with all of the properties.

 
```
// @flow
type One = { foo: number };
type Two = { bar: boolean };

type Both = One & Two;

var value: Both = {
  foo: 1,
  bar: true
};

```
 When you have properties that overlap by having the same name, Flow follows the same strategy as with overloaded functions: it will return the type of the first property that matches this name.

 For example, if you merge two objects with a property named `prop`, first with a type of number and second with a type of boolean, accessing `prop` will return `number`.

 
```
type One = { prop: number };
type Two = { prop: boolean };

declare var both: One & Two;

var prop1: number = both.prop; // okay
var prop2: boolean = both.prop; // Error: number is incompatible with boolean

```
 **Note:** When it comes to objects, the order-specific way in which intersection types are implemented in Flow, may often seem counterintuitive from a set theoretic point of view. In sets, the operands of intersection can change order arbitrarily (commutative property). For this reason, it is a better practice to define this kind of operation over object types using the *spread* operator, e.g. `{ ...One, ...Two }`, where the ordering semantics are better specified.

 Impossible intersection types
-----------------------------

 Using intersection types, it is possible to create types which are impossible to create at runtime. Intersection types will allow you to combine any set of types, even ones that conflict with one another.

 For example, you can create an intersection of a number and a string.

 
```
// @flow
type NumberAndString = number & string;

function method(value: NumberAndString) {
  // ...
}

// $ExpectError
method(3.14); // Error!
// $ExpectError
method('hi'); // Error!

```
 But you can’t possibly create a value which is both a *number and a string*, but you can create a type for it. There’s no practical use for creating types like this, but it’s a side effect of how intersection types work.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/intersections>

Indexed Access Types
====================

 Flow’s Indexed Access Types allow you to get the type of a property from an [object](../objects), [array](../arrays), or [tuple](../tuples) type.

 Indexed Access Types are a replacement for the [`$PropertyType`](../utilities#toc-propertytype) and [`$ElementType`](../utilities#toc-elementtype) utility types. If you’re familiar with those utility types already, here is a quick conversion guide:

 * `$PropertyType<Obj, 'prop'>` → `Obj['prop']`
* `$ElementType<Obj, T>` → `Obj[T]`
* `$ElementType<$PropertyType<Obj, 'prop'>, T>` → `Obj['prop'][T]`

 Indexed Access Type Usage
-------------------------

 Access an object type’s property:

 
```
// @flow
type Cat = {
  name: string,
  age: number,
  hungry: boolean,
};

type Hungry = Cat['hungry']; // type Hungry = boolean
const isHungry: Hungry = true; // OK - `Hungry` is an alias for `boolean`

// The index can be a type, not just a literal:
type AgeProp = 'age';
type Age = Cat[AgeProp]; // type Age = number
const catAge: Age = 6; // OK - `Age` is an alias for `number`

```
 Access an array type’s element, by getting the type at the array’s indices (which are `number`s):

 
```
// @flow
type CatNames = Array<string>;

type CatName = CatNames[number]; // type CatName = string
const myCatsName: CatName = 'whiskers'; // OK - `CatName` is an alias for `string`

```
 Access a tuple type’s elements:

 
```
// @flow
type Pair = [string, number];

const name: Pair[0] = 'whiskers'; // OK - `Pair[0]` is an alias for `string`
const age: Pair[1] = 6; // OK - `Pair[1]` is an alias for `number`
const wrong: Pair[2] = true; // Error - `Pair` only has two elements

```
 The index can be a union, including the result of calling [`$Keys<...>`](../utilities#toc-keys):

 
```
// @flow
type Cat = {
  name: string,
  age: number,
  hungry: boolean,
};

type Values = Cat[$Keys<Cat>]; // type Values = string | number | boolean

```
 The index can also be a generic:

 
```
// @flow
function getProp<O: {+[string]: mixed}, K: $Keys<O>>(o: O, k: K): O[K] {
  return o[k];
}

const x: number = getProp({a: 42}, 'a'); // OK
const y: string = getProp({a: 42}, 'a'); // Error - `number` is not a `string`
getProp({a: 42}, 'b'); // Error - `b` does not exist in object type

```
 You can nest these accesses:

 
```
// @flow
type Cat = {
  name: string,
  age: number,
  hungry: boolean,
  personality: {
    friendly: boolean,
    hungerLevel: number,
  }
};

type Friendly = Cat['personality']['friendly']; // type Friendly = boolean
const isFriendly: Friendly = true; // Pet the cat

```
 Optional Indexed Access Types
-----------------------------

 Optional Indexed Access Types work like optional chaining. They allow you to access properties from nullable object types. If before you did:

 
```
type T = $ElementType<$NonMaybeType<Obj>, 'prop'> | void;

```
 You can now do:

 
```
type T = Obj?.['prop'];

```
 Like optional chaining, the resulting types of Optional Indexed Access Types include `void`. If you have a long chain of nested optional accesses, you can wrap the entire thing with a `$NonMaybeType<...>` if you don’t want `void` in your resulting type.

 Example:

 
```
// @flow
type TasksContent = ?{
  tasks?: Array<{
    items?: {
      metadata?: {
        title: string,
        completed: boolean,
      },
    },
  }>,
};

type TaskData = TasksContent?.['tasks']?.[number]?.['items']?.['metadata'];

```
 There is one small difference between optional chaining and Optional Indexed Access Types. If the object type you access is not nullable, the resulting type in optional chaining will not include `void`. With Optional Indexed Access Types, for implementation reasons, the resulting type will always include `void`. However, if your object type is not nullable then you don’t need to use an Optional Indexed Access Type, but should just use a regular Indexed Access Type.

 Adoption
--------

 To use Indexed Access Types, you need to upgrade your infrastructure so that it supports the syntax:

 * `flow` and `flow-parser`: 0.155
* `prettier`: 2.3.2
* `babel`: 7.14

 We have created an ESLint rule that warns on `$ElementType` and `$PropertyType` usage and recommends Indexed Access Types instead. It includes an auto-fixer that can handle most cases. You can simply enable this rule on your codebase and autofix all existing issues.

 Install [`eslint-plugin-fb-flow`](https://www.npmjs.com/package/eslint-plugin-fb-flow), and add `fb-flow` to your ESLint plugin list. Then enable the rule in your ESLint config:

 
```
'fb-flow/use-indexed-access-type': 1,
```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/indexed-access>

Typeof Types
============

 JavaScript has a `typeof` operator which returns a string describing a value.

 
```
typeof 1 === 'number'
typeof true === 'boolean'
typeof 'three' === 'string'

```
 However it is limited in that this string only describes so much about the type.

 
```
typeof { foo: true } === 'object'
typeof { bar: true } === 'object'
typeof [true, false] === 'object'

```
 In Flow, there is a similar `typeof` operator, but it’s much more powerful.

 
`typeof` type syntax
---------------------

 The `typeof` operator returns the Flow type of a given value to be used as a type.

 
```
// @flow
let num1 = 42;
let num2: typeof num1 = 3.14;     // Works!
// $ExpectError
let num3: typeof num1 = 'world';  // Error!

let bool1 = true;
let bool2: typeof bool1 = false;  // Works!
// $ExpectError
let bool3: typeof bool1 = 42;     // Error!

let str1 = 'hello';
let str2: typeof str1 = 'world'; // Works!
// $ExpectError
let str3: typeof str1 = false;   // Error!

```
 You can use any value with `typeof`:

 
```
// @flow
let obj1 = { foo: 1, bar: true, baz: 'three' };
let obj2: typeof obj1 = { foo: 42, bar: false, baz: 'hello' };

let arr1 = [1, 2, 3];
let arr2: typeof arr1 = [3, 2, 1];

```
 
`typeof` inherits behaviors of inference
-----------------------------------------

 Flow does all sorts of type inference on your code so that you don’t have to type annotate anything. Generally, inference avoids getting in your way while still preventing you from introducing bugs.

 But when you use `typeof`, you’re taking the results of Flow’s inference and asserting it as a type. While this can be very useful, it can also lead to some unexpected results.

 For example, when you use literal values in Flow, their inferred type is the primitive that it belongs to. Thus, the number 42 has the inferred type of `number`. You can see this when you use `typeof`.

 
```
// @flow
let num1 = 42;
let num2: typeof num1 = 3.14;    // Works!

let bool1 = true;
let bool2: typeof bool1 = false; // Works!

let str1 = 'hello';
let str2: typeof str1 = 'world'; // Works!

```
 However, this only happens with the inferred type. If you specify the literal type, it will be used in `typeof`.

 
```
// @flow
let num1: 42 = 42;
// $ExpectError
let num2: typeof num1 = 3.14;    // Error!

let bool1: true = true;
// $ExpectError
let bool2: typeof bool1 = false; // Error!

let str1: 'hello' = 'hello';
// $ExpectError
let str2: typeof str1 = 'world'; // Error!

```
 
`typeof` inherits behaviors of other types
-------------------------------------------

 There are many different types in Flow, some of these types behave differently than others. These differences make sense for that particular type but not for others.

 When you use `typeof`, you’re inserting another type with all of its behaviors. This can make `typeof` seem inconsistent where it is not.

 For example, if you use `typeof` with a class you need to remember that classes are *nominally* typed instead of *structurally* typed. So that two classes with the same exact shape are not considered equivalent.

 
```
// @flow
class MyClass {
  method(val: number) { /* ... */ }
}

class YourClass {
  method(val: number) { /* ... */ }
}

// $ExpectError
let test1: typeof MyClass = YourClass; // Error!
let test2: typeof MyClass = MyClass;   // Works!

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/typeof>

Type Casting Expressions
========================

 Sometimes it is useful to assert a type without using something like a function or a variable to do so. For this Flow supports an inline type cast expression syntax which can be used in a number of different ways.

 Type Cast Expression Syntax
---------------------------

 In order to create a type cast expression around a `value`, add a colon `:` with the `Type` and wrap the expression with parentheses `(` `)`.

 
```
(value: Type)

```
 
>  **Note:** The parentheses are necessary to avoid ambiguity with other syntax.
> 
>  

 Type cast expressions can appear anywhere an expression can appear.

 
```
let val = (value: Type);
let obj = { prop: (value: Type) };
let arr = ([(value: Type), (value: Type)]: Array<Type>);

```
 The value itself can also be an expression:

 
```
(2 + 2: number);

```
 When you strip the types all that is left is the value.

 
```
(value: Type);

```
 
```
value;

```
 Type Assertions
---------------

 Using type cast expressions you can assert that values are certain types.

 
```
// @flow
let value = 42;

(value: 42);     // Works!
(value: number); // Works!
(value: string); // Error!

```
 Asserting types in this way works the same as types do anywhere else.

 Type Casting
------------

 When you write a type cast expression, the result of that expression is the value with the provided type. If you hold onto the resulting value, it will have the new type.

 
```
// @flow
let value = 42;

(value: 42);     // Works!
(value: number); // Works!

let newValue = (value: number);

// $ExpectError
(newValue: 42);     // Error!
(newValue: number); // Works!

```
 Using type cast expressions
---------------------------

 
>  **Note:** We’re going to go through a stripped down example for demonstrating how to make use of type cast expressions. This example is not solved well in practice.
> 
>  

 ### Type Casting through any

 Because type casts work the same as all other type annotations, you can only cast values to less specific types. You cannot change the type or make it something more specific.

 But you can use any to cast to whatever type you want.

 
```
let value = 42;

(value: number); // Works!
// $ExpectError
(value: string); // Error!

let newValue = ((value: any): string);

// $ExpectError
(newValue: number); // Error!
(newValue: string); // Works!

```
 By casting the value to any, you can then cast to whatever you want.

 This is unsafe and not recommended. But it’s sometimes useful when you are doing something with a value which is very difficult or impossible to type and want to make sure that the result has the desired type.

 For example, the following function for cloning an object.

 
```
function cloneObject(obj) {
  const clone = {};

  Object.keys(obj).forEach(key => {
    clone[key] = obj[key];
  });

  return clone;
}

```
 It would be hard to create a type for this because we’re creating a new object based on another object.

 If we cast through any, we can return a type which is more useful.

 
```
// @flow
function cloneObject(obj) {
  const clone = {};

  Object.keys(obj).forEach(key => {
    clone[key] = obj[key];
  });

  return ((clone: any): typeof obj); // <<
}

const clone = cloneObject({
  foo: 1,
  bar: true,
  baz: 'three'
});

(clone.foo: 1);       // Works!
(clone.bar: true);    // Works!
(clone.baz: 'three'); // Works!

```
 ### Type checking through type assertions

 If we want to validate what kinds of types are coming into our `cloneObject` method from before, we could write the following annotation:

 
```
function cloneObject(obj: { [key: string]: mixed }) {
  // ...
}

```
 But now we have a problem. Our `typeof obj` annotation also gets this new annotation which defeats the entire purpose.

 
```
// @flow
function cloneObject(obj: { [key: string]: mixed }) {
  const clone = {};
  // ...
  return ((clone: any): typeof obj);
}

const clone = cloneObject({
  foo: 1,
  bar: true,
  baz: 'three'
});

// $ExpectError
(clone.foo: 1);       // Error!
// $ExpectError
(clone.bar: true);    // Error!
// $ExpectError
(clone.baz: 'three'); // Error!

```
 Instead we can assert the type within the function using a type assertion and now we’re validating our inputs.

 
```
// @flow
function cloneObject(obj) {
  (obj: { [key: string]: mixed });
  // ...
}

cloneObject({ foo: 1 }); // Works!
// $ExpectError
cloneObject([1, 2, 3]);  // Error!

```
 Now type inference can keep working for `typeof obj` which returns the expected shape of the object.

 
```
// @flow
function cloneObject(obj) {
  (obj: { [key: string]: mixed }); // <<

  const clone = {};
  // ...
  return ((clone: any): typeof obj);
}

const clone = cloneObject({
  foo: 1,
  bar: true,
  baz: 'three'
});

(clone.foo: 1);       // Works!
(clone.bar: true);    // Works!
(clone.baz: 'three'); // Works!

```
 
>  **Note:** This is not the proper solution to the above problem, it was being used for demonstration only. The correct solution is annotating the function like this:
> 
>  

 
```
function cloneObject<T: { [key: string]: mixed }>(obj: T): $Shape<T> {
 // ...
}

```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/casting>

Comment Types
=============

 Flow supports a comment-based syntax, which makes it possible to use Flow without having to compile your files.

 
```
// @flow

/*::
type MyAlias = {
  foo: number,
  bar: boolean,
  baz: string,
};
*/

function method(value /*: MyAlias */) /*: boolean */ {
  return value.bar;
}

method({ foo: 1, bar: true, baz: ["oops"] });

```
 These comments allow Flow to work in plain JavaScript files without any additional work.

 Comment types syntax
--------------------

 There are two primary pieces of the syntax: type includes and type annotations.

 ### Comment type include

 If you want to have Flow treat a comment as if it were normal syntax, you can do so by adding a double colon `::` to the start of the comment.

 
```
/*::
type Foo = {
  foo: number,
  bar: boolean,
  baz: string
};
*/

class MyClass {
  /*:: prop: string; */
}

```
 This includes the code into the syntax that Flow sees.

 
```
type Foo = {
  foo: number,
  bar: boolean,
  baz: string
};

class MyClass {
  prop: string;
}

```
 But JavaScript ignores these comments, so all it has is the valid syntax.

 
```
class MyClass {

}

```
 This syntax is also available in a `flow-include` form.

 
```
/*flow-include
type Foo = {
  foo: number,
  bar: boolean,
  baz: string
};
*/

class MyClass {
  /*flow-include prop: string; */
}

```
 ### Comment type annotation

 Instead of typing out a full include every time, you can also use the type annotation shorthand with a single colon `:` at the start of the comment.

 
```
function method(param /*: string */) /*: number */ {
  // ...
}

```
 This would be the same as including a type annotation inside an include comment.

 
```
function method(param /*:: : string */) /*:: : number */ {
  // ...
}

```
 
>  **Note:** If you want to use optional function parameters you’ll need to use the include comment form.
> 
>  

 
>  **Special thanks to**: [Jarno Rantanen](https://github.com/jareware) for building [flotate](https://github.com/jareware/flotate) and supporting us merging his syntax upstream into Flow.
> 
>  



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/comments>

Atom
====

 If you’re using [Atom](https://atom.io) you have a bunch of options to integrate Flow into your code base.

 Flow for Atom IDE
-----------------

 
```
apm install atom-ide-ui && apm install ide-flowtype
```
 [Flow for Atom IDE](https://atom.io/packages/ide-flowtype) is extracted from [Nuclide](https://nuclide.io), and works with the [Atom IDE](https://ide.atom.io/) UI. It brings the core features you expect in a full-featured IDE into Atom, such as language-aware autocomplete, diagnostics, go-to-definition, type hints, and symbol outlines.

 Flow-IDE
--------

 
```
apm install flow-ide
```
 [Flow-IDE](https://atom.io/packages/flow-ide) is a smaller package that only provides you with a linter and autocomplete functionality. It, too, currently lacks support for on-the-fly linting.

 Linter-Flow
-----------

 
```
apm install linter-flow
```
 In case you’re looking for something even more minimal, [linter-flow](https://atom.io/packages/linter-flow) may be worth your attention. It only lints your code and provides no other features, but it does support on-the-fly linting.

 Autocomplete-Flow
-----------------

 
```
apm install autocomplete-flow
```
 [autocomplete-flow](https://atom.io/packages/autocomplete-flow) is another purpose-built tool that only does one thing. This package, as the name suggests, will give your flow enabled code autocomplete suggestions and nothing else.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/editors/atom>

Vim
===

 Flow’s editor integration is primarily via the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/). There are [many vim LSP clients](https://microsoft.github.io/language-server-protocol/implementors/tools/) to choose from, such as [ALE](#toc-ale).

 ALE
---

 The Asynchronous Lint Engine (ALE) plugin for Vim 8+ and NeoVim, [vim-ale](https://github.com/w0rp/ale), is a generalized linting engine with support for Flow and many other tools.

 ### Installation

 Follow the [instructions](https://github.com/w0rp/ale#3-installation) in the ALE README.

 Configure ALE to use the `flow-language-server` linter for JavaScript files:

 
```
" In ~/.vim/ftplugin/javascript.vim, or somewhere similar.

" Enables only Flow for JavaScript. See :ALEInfo for a list of other available
" linters. NOTE: the `flow` linter uses an old API; prefer `flow-language-server`.
let b:ale_linters = ['flow-language-server']

" Or in ~/.vim/vimrc:
let g:ale_linters = {
\   'javascript': ['flow-language-server'],
\}
```
 coc.nvim-neovim
---------------

 [Coc](https://github.com/neoclide/coc.nvim) is an intellisense engine for vim8 & neovim.

 ### Setup

 
```
set nocompatible
filetype off

" install coc.nvim using Plug or preffered plugin manager
call plug#begin('~/.vim/plugged')
Plug 'neoclide/coc.nvim', {'branch': 'release'}
call plug#end()

filetype plugin indent on

" ======= coc settings
set updatetime=300
set shortmess+=c

" Use leader T to show documentation in preview window
nnoremap <leader>t :call <SID>show_documentation()<CR>


function! s:show_documentation()
  if (index(['vim','help'], &filetype) >= 0)
    execute 'h '.expand('&lt;cword&gt;')
  else
    call CocAction('doHover')
  endif
endfunction

" instead of having ~/.vim/coc-settings.json
let s:LSP_CONFIG = {
\  'flow': {
\    'command': exepath('flow'),
\    'args': ['lsp'],
\    'filetypes': ['javascript', 'javascriptreact'],
\    'initializationOptions': {},
\    'requireRootPattern': 1,
\    'settings': {},
\    'rootPatterns': ['.flowconfig']
\  }
\}

let s:languageservers = {}
for [lsp, config] in items(s:LSP_CONFIG)
  let s:not_empty_cmd = !empty(get(config, 'command'))
  if s:not_empty_cmd | let s:languageservers[lsp] = config | endif
endfor

if !empty(s:languageservers)
  call coc#config('languageserver', s:languageservers)
  endif
```
 LanguageClient-neovim
---------------------

 Another way to add support for Flow in Vim is to use [LanguageClient-neovim](https://github.com/autozimu/LanguageClient-neovim).

 * Suports vim 8 and neovim
* Adds completions to omnifunc
* Checks JavaScript files for type errors on save
* Look up types under cursor

 ### Requirements

 * Requires Flow to be installed and available on your path.
* Requires projects containing JavaScript files to be initialised with flow init.
* Requires JavaScript files to be marked with /\* @flow \*/ at the top.

 ### Pathogen

 
```
cd ~/.vim/bundle
git clone git://github.com/autozimu/LanguageClient-neovim.git
```
 ### NeoBundle

 Add this to your ~/.vimrc

 
```
NeoBundleLazy 'autozimu/LanguageClient-neovim', {
    \ 'autoload': {
    \     'filetypes': 'javascript'
    \ }}
```
 With Flow build step, using flow-bin

 
```
NeoBundleLazy 'autozimu/LanguageClient-neovim', {
    \ 'autoload': {
    \     'filetypes': 'javascript'
    \ },
    \ 'build': {
    \     'mac': 'npm install -g flow-bin',
    \     'unix': 'npm install -g flow-bin'
    \ }}
```
 ### VimPlug

 
```
Plug 'autozimu/LanguageClient-neovim', {
    \ 'branch': 'next',
    \ 'do': 'bash install.sh && npm install -g flow-bin',
    \ }
```
 ### Setup

 
```
let g:LanguageClient_rootMarkers = {
\   'javascript': ['.flowconfig', 'package.json']
\ }
let g:LanguageClient_serverCommands={
\   'javascript': ['flow', 'lsp'],
\   'javascript.jsx': ['flow', 'lsp']
\}

" check the type under cursor w/ leader T
nnoremap <leader>t :call LanguageClient_textDocument_hover()<CR>
nnoremap <leader>y :call LanguageClient_textDocument_definition()<CR>
```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/editors/vim>

Emacs
=====

 flow-for-emacs
--------------

 You can add support for Flow in Emacs by using [flow-for-emacs](https://github.com/flowtype/flow-for-emacs)

 Requirements
------------

 * Requires Flow to be installed and available on your path.
* Requires projects containing JavaScript files to be initialised with flow init.
* Requires JavaScript files to be marked with /\* @flow \*/ at the top.

 Installation
------------

 
```
cd ~/.emacs.d/
git clone https://github.com/flowtype/flow-for-emacs.git
echo -e "\n(load-file \"~/.emacs.d/flow-for-emacs/flow.el\")" >> ~/.emacs
```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/editors/emacs>

WebStorm
========

 Webstorm installation instructions can be found here:

 * [WebStorm 2016.3](https://www.jetbrains.com/help/webstorm/2016.3/using-the-flow-type-checker.html)
* [WebStorm 2017.1](https://www.jetbrains.com/help/webstorm/2017.1/flow-type-checker.html)



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/editors/webstorm>

Utility Types
=============

 Flow provides a set of utility types to operate on other types, and can be useful for different scenarios.

 Table of contents:

 * [`$Keys<T>`](#toc-keys)
* [`$Values<T>`](#toc-values)
* [`$ReadOnly<T>`](#toc-readonly)
* [`$Exact<T>`](#toc-exact)
* [`$Diff<A, B>`](#toc-diff)
* [`$Rest<A, B>`](#toc-rest)
* [`$PropertyType<T, k>`](#toc-propertytype)
* [`$ElementType<T, K>`](#toc-elementtype)
* [`$NonMaybeType<T>`](#toc-nonmaybe)
* [`$ObjMap<T, F>`](#toc-objmap)
* [`$ObjMapi<T, F>`](#toc-objmapi)
* [`$ObjMapConst<O, T>`](#toc-objmapconst)
* [`$KeyMirror<O>`](#toc-keymirror)
* [`$TupleMap<T, F>`](#toc-tuplemap)
* [`$Call<F, T...>`](#toc-call)
* [`Class<T>`](#toc-class)
* [`$Shape<T>`](#toc-shape)
* [`$Exports<T>`](#toc-exports)
* [`$Supertype<T>`](#toc-supertype)
* [`$Subtype<T>`](#toc-subtype)
* [`Existential Type (*)`](#toc-existential-type)

 
`$Keys<T>`
-----------

 In Flow you can [use union types similar to enums](../literals):

 
```
// @flow
type Suit = "Diamonds" | "Clubs" | "Hearts" | "Spades";

const clubs: Suit = 'Clubs';
const wrong: Suit = 'wrong'; // 'wrong' is not a Suit

```
 This is very handy, but sometimes you need to access the enum definition at runtime (i.e. at a value level).

 Suppose for example that you want to associate a value to each suit of the previous example.

 You could do

 
```
// @flow
type Suit = "Diamonds" | "Clubs" | "Hearts" | "Spades";

const suitNumbers = {
  Diamonds: 1,
  Clubs: 2,
  Hearts: 3,
  Spades: 4
};

function printSuitNumber(suit: Suit) {
  console.log(suitNumbers[suit]);
}

printSuitNumber('Diamonds'); // 1
printSuitNumber('foo'); // 'foo' is not a Suit

```
 but this doesn’t feel very DRY, as we had to explicitly define the suit names twice.

 In situations like this one, you can leverage the `$Keys<T>` operator. Let’s see another example, this time using `$Keys`:

 
```
// @flow
const countries = {
  US: "United States",
  IT: "Italy",
  FR: "France"
};

type Country = $Keys<typeof countries>;

const italy: Country = 'IT';
const nope: Country = 'nope'; // 'nope' is not a Country

```
 In the example above, the type of `Country` is equivalent to `type Country = 'US' | 'IT' | 'FR'`, but Flow was able to extract it from the keys of `countries`.

 
`$Values<T>`
-------------

 `$Values<T>` represents the union type of all the value types (not the values, but their *types*!) of the enumerable properties in an [Object Type](../objects) `T`.

 For example:

 
```
// @flow
type Props = {
  name: string,
  age: number,
};

// The following two types are equivalent:
type PropValues = string | number;
type Prop$Values = $Values<Props>;

const name: Prop$Values = 'Jon';  // OK
const age: Prop$Values = 42;  // OK
const fn: Prop$Values = () => {};  // Error! function is not part of the union type

```
 
`$ReadOnly<T>`
---------------

 `$ReadOnly<T>` is a type that represents the read-only version of a given [object type](../objects) `T`. A read-only object type is an object type whose keys are all [read-only](../interfaces#toc-interface-property-variance-read-only-and-write-only).

 This means that the following 2 types are equivalent:

 
```
type ReadOnlyObj = {
  +key: any,  // read-only field, marked by the `+` annotation
};

```
 
```
type ReadOnlyObj = $ReadOnly<{
  key: any,
}>;

```
 This is useful when you need to use a read-only version of an object type you’ve already defined, without manually having to re-define and annotate each key as read-only. For example:

 
```
// @flow
type Props = {
  name: string,
  age: number,
  // ...
};

type ReadOnlyProps = $ReadOnly<Props>;

function render(props: ReadOnlyProps) {
  const {name, age} = props;  // OK to read
  props.age = 42;             // Error when writing
  // ...
}

```
 Additionally, other utility types, such as [`$ObjMap<T>`](#toc-objmap), may strip any read/write annotations, so `$ReadOnly<T>` is a handy way to quickly make the object read-only again after operating on it:

 
```
type Obj = {
  +key: any,
};

type MappedObj = $ReadOnly<$ObjMap<Obj, TypeFn>> // Still read-only

```
 
>  Note: `$ReadOnly` is only for making read-only *object* types. See the Array docs for how to [type read-only arrays with `$ReadOnlyArray`](../arrays#toc-readonlyarray).
> 
>  

 
`$Exact<T>`
------------

 `$Exact<{name: string}>` is a synonym for `{| name: string |}` as in the [Object documentation](../objects#toc-exact-object-types).

 
```
// @flow
type ExactUser = $Exact<{name: string}>;
type ExactUserShorthand = {| name: string |};

const user2 = {name: 'John Wilkes Booth'};
// These will both be satisfied because they are equivalent
(user2: ExactUser);
(user2: ExactUserShorthand);

```
 
`$Diff<A, B>`
--------------

 As the name hints, `$Diff<A, B>` is the type representing the set difference of `A` and `B`, i.e. `A \ B`, where `A` and `B` are both [object types](../objects). Here’s an example:

 
```
// @flow
type Props = { name: string, age: number };
type DefaultProps = { age: number };
type RequiredProps = $Diff<Props, DefaultProps>;

function setProps(props: RequiredProps) {
  // ...
}

setProps({ name: 'foo' });
setProps({ name: 'foo', age: 42, baz: false }); // you can pass extra props too
setProps({ age: 42 }); // error, name is required

```
 As you may have noticed, the example is not a random one. `$Diff` is exactly what the React definition file uses to define the type of the props accepted by a React Component.

 Note that `$Diff<A, B>` will error if the object you are removing properties from does not have the property being removed, i.e. if `B` has a key that doesn’t exist in `A`:

 
```
// @flow
type Props = { name: string, age: number };
type DefaultProps = { age: number, other: string }; // Will error due to this `other` property not being in Props.
type RequiredProps = $Diff<Props, DefaultProps>;

function setProps(props: RequiredProps) {
  props.name;
  // ...
}

```
 As a workaround, you can specify the property not present in `A` as optional. For example:

 
```
type A = $Diff<{}, {nope: number}>; // Error
type B = $Diff<{}, {nope: number | void}>; // OK

```
 
`$Rest<A, B>`
--------------

 `$Rest<A, B>` is the type that represents the runtime object rest operation, e.g.: `const {foo, ...rest} = obj`, where `A` and `B` are both [object types](../objects). The resulting type from this operation will be an object type containing `A`’s *own* properties that are not *own* properties in `B`. In flow, we treat all properties on [exact object types](../objects#toc-exact-object-types) as [own](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty). In in-exact objects, a property may or may not be own.

 For example:

 
```
// @flow
type Props = { name: string, age: number };

const props: Props = {name: 'Jon', age: 42};
const {age, ...otherProps} = props;
(otherProps: $Rest<Props, {|age: number|}>);
otherProps.age;  // Error

```
 The main difference with [`$Diff<A, B>`](#toc-diff), is that `$Rest<A, B>` aims to represent the true runtime rest operation, which implies that exact object types are treated differently in `$Rest<A, B>`. For example, `$Rest<{|n: number|}, {}>` will result in `{|n?: number|}` because an in-exact empty object may have an `n` property, while `$Diff<{|n: number|}, {}>` will result in `{|n: number|}`.

 
`$PropertyType<T, k>`
----------------------

 **WARNING:** `$PropertyType` is deprecated as of Flow version 0.155, and will be removed in a future version of Flow. Use [Indexed Access Types](../indexed-access) instead. `$PropertyType<T, 'k'>` is now `T['k']`.

 A `$PropertyType<T, k>` is the type at a given key `k`. As of Flow v0.36.0, `k` must be a literal string.

 
```
// @flow
type Person = {
  name: string,
  age: number,
  parent: Person
};

const newName: $PropertyType<Person, 'name'> = 'Toni Braxton';
const newAge: $PropertyType<Person, 'age'> = 51;
const newParent: $PropertyType<Person, 'parent'> = 'Evelyn Braxton';

```
 This can be especially useful for referring to the type of React props, or, even the entire `props` type itself.

 
```
// @flow
import React from 'react';

type Props = {
  text: string,
  onMouseOver: ({x: number, y: number}) => void
}

class Tooltip extends React.Component<Props> {
  props: Props;
}

const someProps: $PropertyType<Tooltip, 'props'> = {
  text: 'foo',
  onMouseOver: (data: {x: number, y: number}) => undefined
};

const otherProps: $PropertyType<Tooltip, 'props'> = {
  text: 'foo'
  // Missing the `onMouseOver` definition
};

```
 You can even nest lookups:

 
```
// @flow
type PositionHandler = $PropertyType<$PropertyType<Tooltip, 'props'>, 'onMouseOver'>;
const handler: PositionHandler = (data: {x: number, y: number}) => undefined;
const handler2: PositionHandler = (data: string) => undefined; // wrong parameter types

```
 You can use this in combination with `Class<T>` to get static props:

 
```
// @flow
class BackboneModel {
  static idAttribute: string | false;
}

type ID = $PropertyType<Class<BackboneModel>, 'idAttribute'>;
const someID: ID = '1234';
const someBadID: ID = true;

```
 
`$ElementType<T, K>`
---------------------

 **WARNING:** `$ElementType` is deprecated as of Flow version 0.155, and will be removed in a future version of Flow. Use [Indexed Access Types](../indexed-access) instead. `$ElementType<T, K>` is now `T[K]`.

 `$ElementType<T, K>` is the type that represents the type of every element inside an [array](../arrays), [tuple](../tuples) or [object](../objects) type `T`, that matches the given *key* type `K`.

 For example:

 
```
// @flow

// Using objects:
type Obj = {
  name: string,
  age: number,
}
('Jon': $ElementType<Obj, 'name'>);
(42: $ElementType<Obj, 'age'>);
(true: $ElementType<Obj, 'name'>); // Nope, `name` is not a boolean
(true: $ElementType<Obj, 'other'>); // Nope, property `other` is not in Obj

// Using tuples:
type Tuple = [boolean, string];
(true: $ElementType<Tuple, 0>);
('foo': $ElementType<Tuple, 1>);
('bar': $ElementType<Tuple, 2>); // Nope, can't access position 2

```
 In the above case, we’re using literal values as `K`, similarly to [`$PropertyType<T, k>`](#toc-propertytype). However, when using `$ElementType<T, K>`, `K` is allowed to be any type, as long as that type exists on the keys of `T`. For example:

 
```
// @flow

// Using objects
type Obj = { [key: string]: number };
(42: $ElementType<Obj, string>);
(42: $ElementType<Obj, boolean>); // Nope, object keys aren't booleans
(true: $ElementType<Obj, string>); // Nope, elements are numbers


// Using arrays, we don't statically know the size of the array, so you can just use the `number` type as the key:
type Arr = Array<boolean>;
(true: $ElementType<Arr, number>);
(true: $ElementType<Arr, boolean>); // Nope, array indices aren't booleans
('foo': $ElementType<Arr, number>); // Nope, elements are booleans

```
 You can also nest calls to `$ElementType<T, K>`, which is useful when you need to access the types inside nested structures:

 
```
// @flow
type NumberObj = {
  nums: Array<number>,
};

(42: $ElementType<$ElementType<NumberObj, 'nums'>, number>);

```
 Additionally, one of the things that also makes `$ElementType<T, K>` more powerful than [`$PropertyType<T, k>`](#toc-propertytype) is that you can use it with generics. For example:

 
```
// @flow
function getProp<O: {+[string]: mixed}, P: $Keys<O>>(o: O, p: P): $ElementType<O, P> {
  return o[p];
}

(getProp({a: 42}, 'a'): number); // OK
(getProp({a: 42}, 'a'): string); // Error: number is not a string
getProp({a: 42}, 'b'); // Error: `b` does not exist

```
 
`$NonMaybeType<T>`
-------------------

 `$NonMaybeType<T>` converts a type `T` to a non-maybe type. In other words, the values of `$NonMaybeType<T>` are the values of `T` except for `null` and `undefined`.

 
```
// @flow
type MaybeName = ?string;
type Name = $NonMaybeType<MaybeName>;

('Gabriel': MaybeName); // Ok
(null: MaybeName); // Ok
('Gabriel': Name); // Ok
(null: Name); // Error! null can't be annotated as Name because Name is not a maybe type

```
 
`$ObjMap<T, F>`
----------------

 `ObjMap<T, F>` takes an [object type](../objects) `T`, and a [function type](../functions) `F`, and returns the object type obtained by mapping the type of each value in the object with the provided function type `F`. In other words, `$ObjMap` will [call](#toc-call) (at the type level) the given function type `F` for every property value type in `T`, and return the resulting object type from those calls.

 Let’s see an example. Suppose you have a function called `run` that takes an object of thunks (functions in the form `() => A`) as input:

 
```
// @flow
function run<O: {[key: string]: Function}>(o: O) {
  return Object.keys(o).reduce((acc, k) => Object.assign(acc, { [k]: o[k]() }), {});
}

```
 The function’s purpose is to run all the thunks and return an object made of values. What’s the return type of this function?

 The keys are the same, but the values have a different type, namely the return type of each function. At a value level (the implementation of the function) we’re essentially mapping over the object to produce new values for the keys. How to express this at a type level?

 This is where `ObjMap<T, F>` comes in handy.

 
```
// @flow

// let's write a function type that takes a `() => V` and returns a `V` (its return type)
type ExtractReturnType = <V>(() => V) => V;

declare function run<O: {[key: string]: Function}>(o: O): $ObjMap<O, ExtractReturnType>;

const o = {
  a: () => true,
  b: () => 'foo'
};

(run(o).a: boolean); // Ok
(run(o).b: string);  // Ok
// $ExpectError
(run(o).b: boolean); // Nope, b is a string
// $ExpectError
run(o).c;            // Nope, c was not in the original object

```
 This is extremely useful for expressing the return type of functions that manipulate objects values. You could use a similar approach (for instance) to provide the return type of bluebird’s [`Promise.props`](http://bluebirdjs.com/docs/api/promise.props.html) function, which is like `Promise.all` but takes an object as input.

 Here’s a possible declaration of this function, which is very similar to our first example:

 
```
// @flow
declare function props<A, O: { [key: string]: A }>(promises: O): Promise<$ObjMap<O, typeof $await>>;

```
 And use:

 
```
// @flow
const promises = { a: Promise.resolve(42) };
props(promises).then(o => {
  (o.a: 42); // Ok
  // $ExpectError
  (o.a: 43); // Error, flow knows it's 42
});

```
 
`$ObjMapi<T, F>`
-----------------

 `ObjMapi<T, F>` is similar to [`ObjMap<T, F>`](#toc-objmap). The difference is that function type `F` will be [called](#toc-call) with both the key and value types of the elements of the object type `T`, instead of just the value types. For example:

 
```
// @flow
const o = {
  a: () => true,
  b: () => 'foo'
};

type ExtractReturnObjectType = <K, V>(K, () => V) => { k: K, v: V };

declare function run<O: {...}>(o: O): $ObjMapi<O, ExtractReturnObjectType>;

(run(o).a: { k: 'a', v: boolean }); // Ok
(run(o).b: { k: 'b', v: string });  // Ok
// $ExpectError
(run(o).a: { k: 'b', v: boolean }); // Nope, a.k is "a"
// $ExpectError
(run(o).b: { k: 'b', v: number });  // Nope, b.v is a string
// $ExpectError
run(o).c;                           // Nope, c was not in the original object

```
 
`$ObjMapConst<O, T>`
---------------------

 `$ObjMapConst<Obj, T>` is a special case of `$ObjMap<Obj, F>`, when `F` is a constant function type, e.g. `() => T`. Instead of writing `$ObjMap<Obj, () => T>`, you can write `$ObjMapConst<Obj, T>`. For example:

 
```
// @flow
const obj = {
  a: true,
  b: 'foo'
};

declare function run<O: {...}>(o: O): $ObjMapConst<O, number>;

// newObj is of type {a: number, b: number}
const newObj = run(obj);

(newObj.a: number); // Ok
// $ExpectedError
(newObj.b: string); // Error property b is a number

```
 Tip: Prefer using `$ObjMapConst` instead of `$ObjMap` (if possible) to fix certain kinds of `[invalid-exported-annotation]` errors.

 
`$KeyMirror<O>`
----------------

 `$KeyMirror<Obj>` is a special case of `$ObjMapi<Obj, F>`, when `F` is the identity function type, ie. `<K>(K) => K`. In other words, it maps each property of an object to the type of the property key. Instead of writing `$ObjMapi<Obj, <K>(K) => K>`, you can write `$KeyMirror<Obj>`. For example:

 
```
// @flow
const obj = {
  a: true,
  b: 'foo'
};

declare function run<O: {...}>(o: O): $KeyMirror<O>;

// newObj is of type {a: 'a', b: 'b'}
const newObj = run(obj);

(newObj.a: 'a'); // Ok
// $ExpectedError
(newObj.b: 'a'); // Error string 'b' is incompatible with 'a'

```
 Tip: Prefer using `$KeyMirror` instead of `$ObjMapi` (if possible) to fix certain kinds of `[invalid-exported-annotation]` errors.

 
`$TupleMap<T, F>`
------------------

 `$TupleMap<T, F>` takes an iterable type `T` (e.g.: [`Tuple`](../tuples) or [`Array`](../arrays)), and a [function type](../functions) `F`, and returns the iterable type obtained by mapping the type of each value in the iterable with the provided function type `F`. This is analogous to the Javascript function `map`.

 Following our example from [`$ObjMap<T>`](#toc-objmap), let’s assume that `run` takes an array of functions, instead of an object, and maps over them returning an array of the function call results. We could annotate its return type like this:

 
```
// @flow

// Function type that takes a `() => V` and returns a `V` (its return type)
type ExtractReturnType = <V>(() => V) => V

function run<A, I: Array<() => A>>(iter: I): $TupleMap<I, ExtractReturnType> {
  return iter.map(fn => fn());
}

const arr = [() => 'foo', () => 'bar'];
(run(arr)[0]: string); // OK
(run(arr)[1]: string); // OK
(run(arr)[1]: boolean); // Error

```
 
`$Call<F, T...>`
-----------------

 `$Call<F, T...>` is a type that represents the result of calling the given [function type](../functions) `F` with 0 or more arguments `T...`. This is analogous to calling a function at runtime (or more specifically, it’s analogous to calling [`Function.prototype.call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call)), but at the type level; this means that function type calls happens statically, i.e. not at runtime.

 Let’s see a couple of examples:

 
```
// @flow

// Takes an object type, returns the type of its `prop` key
type ExtractPropType = <T>({prop: T}) => T;
type Obj = {prop: number};
type PropType = $Call<ExtractPropType, Obj>;  // Call `ExtractPropType` with `Obj` as an argument
type Nope = $Call<ExtractPropType, {nope: number}>;  // Error: argument doesn't match `Obj`.

(5: PropType); // OK
(true: PropType);  // Error: PropType is a number
(5: Nope);  // Error

```
 
```
// @flow

// Takes a function type, and returns its return type
// This is useful if you want to get the return type of some function without actually calling it at runtime.
type ExtractReturnType = <R>(() => R) => R;
type Fn = () => number;
type ReturnType = $Call<ExtractReturnType, Fn> // Call `ExtractReturnType` with `Fn` as an argument

(5: ReturnType);  // OK
(true: ReturnType);  // Error: ReturnType is a number

```
 `$Call` can be very powerful because it allows you to make calls in type-land that you would otherwise have to do at runtime. The type-land calls happen statically and will be erased at runtime.

 Let’s look at a couple of more advanced examples:

 
```
// @flow

// Extracting deeply nested types:
type NestedObj = {|
  +status: ?number,
  +data: ?$ReadOnlyArray<{|
    +foo: ?{|
       +bar: number,
    |},
  |}>,
|};

// If you wanted to extract the type for `bar`, you could use $Call:
type BarType = $Call<
  <T>({
    +data: ?$ReadOnlyArray<{
      +foo: ?{
        +bar: ?T
      },
    }>,
  }) => T,
  NestedObj,
>;

(5: BarType);
(true: BarType);  // Error: `bar` is not a boolean

```
 
```
// @flow

// Getting return types:
function getFirstValue<V>(map: Map<string, V>): ?V {
  for (const [key, value] of map.entries()) {
    return value;
  }
  return null;
}

// Using $Call, we can get the actual return type of the function above, without calling it at runtime:
type Value = $Call<typeof getFirstValue, Map<string, number>>;

(5: Value);
(true: Value);  // Error: Value is a `number`


// We could generalize it further:
type GetMapValue<M> =
  $Call<typeof getFirstValue, M>;

(5: GetMapValue<Map<string, number>>);
(true: GetMapValue<Map<string, boolean>>);
(true: GetMapValue<Map<string, number>>);  // Error: value is a `number`

```
 
`Class<T>`
-----------

 Given a type `T` representing instances of a class `C`, the type `Class<T>` is the type of the class `C`. For example:

 
```
// @flow
class Store {}
class ExtendedStore extends Store {}
class Model {}

function makeStore(storeClass: Class<Store>) {
  return new storeClass();
}

(makeStore(Store): Store);
(makeStore(ExtendedStore): Store);
(makeStore(Model): Model); // error
(makeStore(ExtendedStore): Model); // Flow infers the return type

```
 For classes that take type parameters, you must also provide the parameter. For example:

 
```
// @flow
class ParamStore<T> {
  constructor(data: T) {}
}

function makeParamStore<T>(storeClass: Class<ParamStore<T>>, data: T): ParamStore<T> {
  return new storeClass(data);
}
(makeParamStore(ParamStore, 1): ParamStore<number>);
(makeParamStore(ParamStore, 1): ParamStore<boolean>); // failed because of the second parameter

```
 
`$Shape<T>`
------------

 A variable of type `$Shape<T>`, where `T` is some object type, can be assigned objects `o` that contain a subset of the properties included in `T`. For each property `p: S` of `T`, the type of a potential binding of `p` in `o` must be compatible with `S`.

 For example

 
```
// @flow
type Person = {
  age: number,
  name: string,
}
type PersonDetails = $Shape<Person>;

const person1: Person = {age: 28};  // Error: missing `name`
const person2: Person = {name: 'a'};  // Error: missing `age`
const person3: PersonDetails = {age: 28};  // OK
const person4: PersonDetails = {name: 'a'};  // OK
const person5: PersonDetails = {age: 28, name: 'a'};  // OK
const person6: PersonDetails = {age: '28'};  // Error: string is incompatible with number

```
 
>  Note: `$Shape<T>` is **not** equivalent to `T` with all its fields marked as optional. In particular, Flow unsoundly allows `$Shape<T>` to be used as a `T` in several contexts. For example in
> 
>  
> ```
> const personShape: PersonDetails = {age: 28};
> (personShape: Person);
> ```
>  Flow will unsoundly allow this last cast to succeed. If this behavior is not wanted, then this utility type should be avoided.
> 
>  

 
`$Exports<T>`
--------------

 The following are functionally equivalent

 
```
import typeof * as T from 'my-module';

```
 
```
type T = $Exports<'my-module'>;

```
 The advantage of the `$Exports` syntax is that you can `export` the type on the same line

 
```
export type T = $Exports<'my-module'>;

```
 where as you would otherwise need to export an alias in the `import typeof` case

 
```
import typeof * as T from 'my-module';
export type MyModuleType = T;

```
 
`$Supertype<T>`
----------------

 This utility has been deprecated and should be avoided. See [here](https://flow.org/en/linting/rule-reference/#toc-deprecated-utility) for details.

 
`$Subtype<T>`
--------------

 This utility has been deprecated and should be avoided. See [here](https://flow.org/en/linting/rule-reference/#toc-deprecated-utility) for details.

 Existential Type (`*`)
----------------------

 This utility has been deprecated and should be avoided. See [here](https://flow.org/en/linting/rule-reference/#toc-deprecated-type) for details.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/types/utilities>

.flowconfig [include]
=====================

 Flow needs to know which files to read and watch for changes. This set of files is determined by taking all included files and excluding all the ignored files.

 The `[include]` section in a `.flowconfig` file tells Flow to include the specified files or directories. Including a directory recursively includes all the files under that directory. Symlinks are followed as long as they lead to a file or directory that is also included. Each line in the include section is a path to include. These paths can be relative to the root directory or absolute, and support both single and double star wildcards.

 The project root directory (where your `.flowconfig` lives) is automatically included.

 For example, if `/path/to/root/.flowconfig` contains the following `[include]` section:

 
```
[include]
../externalFile.js
../externalDir/
../otherProject/*.js
../otherProject/**/coolStuff/
```
 Then when Flow checks the project in `/path/to/root`, it will read and watch

 1. `/path/to/root/` (automatically included)
2. `/path/to/externalFile.js`
3. `/path/to/externalDir/`
4. Any file in `/path/to/otherProject/` that ends in `.js`
5. Any directory under `/path/to/otherProject` named `coolStuff/`



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/config/include>

.flowconfig [ignore]
====================

 Flow needs to know which files to read and watch for changes. This set of files is determined by taking all included files and excluding all the ignored files.

 
`[ignore]`
-----------

 The `[ignore]` section in a `.flowconfig` file tells Flow to ignore files matching the specified regular expressions when type checking your code. By default, nothing is ignored.

 Things to keep in mind:

 1. These are [OCaml regular expressions](http://caml.inria.fr/pub/docs/manual-ocaml/libref/Str.html#TYPEregexp).
2. These regular expressions match against absolute paths. They probably should start with `.*`
3. Ignores are processed AFTER includes. If you both include and ignore a file it will be ignored.

 An example `[ignore]` section might look like:

 
```
[ignore]
.*/__tests__/.*
.*/src/\(foo\|bar\)/.*
.*\.ignore\.js
```
 This `[ignore]` section will ignore:

 1. Any file or directory under a directory named `__tests__`
2. Any file or directory under `.*/src/foo` or under `.*/src/bar`
3. Any file that ends with the extension `.ignore.js`

 Starting with Flow v0.23.0, you may use the `<PROJECT_ROOT>` placeholder in your regular expressions. At runtime, Flow will treat the placeholder as if it were the absolute path to the project’s root directory. This is useful for writing regular expressions that are relative rather than absolute.

 For example, you can write:

 
```
[ignore]
<PROJECT_ROOT>/__tests__/.*
```
 Which would ignore any file or directory under the directory named `__tests__/` within the project root. However, unlike the previous example’s `.*/__tests__/.*`, it would NOT ignore files or directories under other directories named `__tests__/`, like `src/__tests__/`.

 Exclusions
----------

 Sometimes you may want to ignore all files inside a directory with the exception of a few. An optional prefix “!” which negates the pattern may help. With this, any matching file excluded by a previous pattern will become included again.

 
```
[ignore]
<PROJECT_ROOT>/node_modules/.*
!<PROJECT_ROOT>/node_modules/not-ignored-package-A/.*
!<PROJECT_ROOT>/node_modules/not-ignored-package-B/.*
```


 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/config/ignore>

.flowconfig [untyped]
=====================

 Flow needs to know which files to parse and of those how to handle any Flow types within them. For third party libraries you may wish to not parse, parse but not preserve types, or parse but not raise errors, depending on the quality and compatibility of their Flow implementation.

 Different sections are available to specify different behaviours, and by combining them most use cases are expected to be met.

 
`[untyped]`
------------

 The `[untyped]` section in a `.flowconfig` file tells Flow to not typecheck files matching the specified regular expressions and instead throw away types and treat modules as `any`.

 This is different from the `[ignore]` config section that causes matching files to be ignored by the module resolver, which inherently makes them un-typechecked, and also unresolvable by `import` or `require`. When ignored `[libs]` must then be specified for each `import` using `flow-typed`, which may not always be desired.

 It is also different from the `[declarations]` section. This also does not typecheck the file contents, but `[declarations]` does extract and use the signatures of functions, classes, etc, when checking other code.

 `[untyped]` instead causes a file to be ignored by the typechecker as if it had `noflow` in it, resolve modules as `any` type, but allow them to NOT be ignored by the module resolver. Any matching file is skipped by Flow (not even parsed, like other `noflow` files!), but can still be `require()`‘d.

 Things to keep in mind:

 1. These are [OCaml regular expressions](http://caml.inria.fr/pub/docs/manual-ocaml/libref/Str.html#TYPEregexp).
2. These regular expressions match against absolute paths. They probably should start with `.*`

 An example `[untyped]` section might look like:

 
```
[untyped]
.*/third_party/.*
.*/src/\(foo\|bar\)/.*
.*\.untype\.js
```
 This `[untyped]` section will parse:

 1. Any file or directory under a directory named `third_party`
2. Any file or directory under `.*/src/foo` or under `.*/src/bar`
3. Any file that ends with the extension `.untype.js`

 Starting with Flow v0.23.0, you may use the `<PROJECT_ROOT>` placeholder in your regular expressions. At runtime, Flow will treat the placeholder as if it were the absolute path to the project’s root directory. This is useful for writing regular expressions that are relative rather than absolute.

 For example, you can write:

 
```
[untyped]
<PROJECT_ROOT>/third_party/.*
```
 Which would parse in declaration mode any file or directory under the directory named `third_party/` within the project root. However, unlike the previous example’s `.*/third_party/.*`, it would NOT parse files or directories under directories named `third_party/`, like `src/third_party/`.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/config/untyped>

.flowconfig [libs]
==================

 The `[libs]` section in a `.flowconfig` file tells Flow to include the specified [library definitions](https://flow.org/en/libdefs/) when type checking your code. Multiple libraries can be specified. By default, the `flow-typed` folder in your project root directory is included as a library directory. This default allows you to use [`flow-typed`](https://github.com/flowtype/flow-typed) to install library definitions without additional configuration.

 Each line in the `[libs]` section is a path to the library file or directory which you would like to include. These paths can be relative to the project root directory or absolute. Including a directory recursively includes all the files under that directory as library files.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/config/libs>

.flowconfig [version]
=====================

 You can specify in the `.flowconfig` which version of Flow you expect to use. You do this with the `[version]` section. If this section is omitted or left blank, then any version is allowed. If a version is specified and not matched, then Flow will immediately error and exit.

 So if you have the following in your `.flowconfig`:

 
```
[version]
0.22.0
```
 and you try to use Flow v0.21.0, then Flow will immediately error with the message

 `"Wrong version of Flow. The config specifies version 0.22.0 but this is version
0.21.0"`

 So far, we support the following ways to specify supported versions

 * Explicit versions, (e.g. `0.22.0`, which only matches `0.22.0`).
* Intersection ranges, which are ANDed together, (e.g. `>=0.13.0 <0.14.0`, which matches `0.13.0` and `0.13.5` but not `0.14.0`).
* Caret ranges, which allow changes that do not modify the left-most non-zero digit (e.g. `^0.13.0` expands into `>=0.13.0 <0.14.0`, and `^0.13.1` expands into `>=0.13.1 <0.14.0`, whereas `^1.2.3` expands into `>=1.2.3 <2.0.0`).



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/config/version>

.flowconfig [lints]
===================

 The `[lints]` section in a `.flowconfig` file can contain several key-value pairs of the form:

 
```
[lints]
ruleA=severityA
ruleB=severityB
```
 Check out the [linting docs](https://flow.org/en/linting) for more information.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/config/lints>

.flowconfig [declarations]
==========================

 Often third-party libraries have broken type definitions or have type definitions only compatible with a certain version of Flow. In those cases it may be useful to use type information from the third-party libraries without typechecking their contents.

 
`[declarations]`
-----------------

 The `[declarations]` section in a `.flowconfig` file tells Flow to parse files matching the specified regular expressions in *declaration mode*. In declaration mode the code is not typechecked. However, the signatures of functions, classes, etc are extracted and used by the typechecker when checking other code.

 Conceptually one can think of declaration mode as if Flow still typechecks the files but acts as if there is a comment that matches [`suppress_comment`](../options#toc-suppress-comment-regex) on every line.

 See also `[untyped]`(untyped) for not typechecking files, and instead using `any` for all contents.

 Things to keep in mind:

 1. Declaration mode should only be used for existing third-party code. You should never use this for code under your control.
2. These are [OCaml regular expressions](http://caml.inria.fr/pub/docs/manual-ocaml/libref/Str.html#TYPEregexp).
3. These regular expressions match against absolute paths. They probably should start with `.*`

 An example `[declarations]` section might look like:

 
```
[declarations]
.*/third_party/.*
.*/src/\(foo\|bar\)/.*
.*\.decl\.js
```
 This `[declarations]` section will parse in declaration mode:

 1. Any file or directory under a directory named `third_party`
2. Any file or directory under `.*/src/foo` or under `.*/src/bar`
3. Any file that ends with the extension `.decl.js`

 Starting with Flow v0.23.0, you may use the `<PROJECT_ROOT>` placeholder in your regular expressions. At runtime, Flow will treat the placeholder as if it were the absolute path to the project’s root directory. This is useful for writing regular expressions that are relative rather than absolute.

 For example, you can write:

 
```
[declarations]
<PROJECT_ROOT>/third_party/.*
```
 Which would parse in declaration mode any file or directory under the directory named `third_party/` within the project root. However, unlike the previous example’s `.*/third_party/.*`, it would NOT parse files or directories under directories named `third_party/`, like `src/third_party/`.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/config/declarations>

.flowconfig [options]
=====================

 The `[options]` section in a `.flowconfig` file can contain several key-value pairs of the form:

 
```
[options]
keyA=valueA
keyB=valueB
```
 Any options that are omitted will use their default values. Some options can be overridden with command line flags.

 Available options
-----------------

 * [`all`](#toc-all-boolean)
* [`autoimports`](#toc-autoimports-boolean)
* [`babel_loose_array_spread`](#toc-babel-loose-array-spread-boolean)
* [`emoji`](#toc-emoji-boolean)
* [`exact_by_default`](#toc-exact-by-default-boolean)
* [`experimental.const_params`](#toc-experimental-const-params-boolean)
* [`include_warnings`](#toc-include-warnings-boolean)
* [`inference_mode`](#toc-inference-mode-classic-constrain-writes)
* [`lazy_mode`](#toc-lazy-mode-boolean)
* [`log.file`](#toc-log-file-string)
* [`max_header_tokens`](#toc-max-header-tokens-integer)
* [`module.file_ext`](#toc-module-file-ext-string)
* [`module.ignore_non_literal_requires`](#toc-module-ignore-non-literal-requires-boolean)
* [`module.name_mapper`](#toc-module-name-mapper-regex-string)
* [`module.name_mapper.extension`](#toc-module-name-mapper-extension-string-string)
* [`module.system`](#toc-module-system-node-haste)
* [`module.system.node.main_field`](#toc-module-system-node-main-field-string)
* [`module.system.node.resolve_dirname`](#toc-module-system-node-resolve-dirname-string)
* [`module.use_strict`](#toc-module-use-strict-boolean)
* [`munge_underscores`](#toc-munge-underscores-boolean)
* [`no_flowlib`](#toc-no-flowlib-boolean)
* [`react.runtime`](#toc-react-runtime-automatic-classic)
* [`server.max_workers`](#toc-server-max-workers-integer)
* [`sharedmemory.dirs`](#toc-sharedmemory-dirs-string)
* [`sharedmemory.minimum_available`](#toc-sharedmemory-minimum-available-unsigned-integer)
* [`sharedmemory.hash_table_pow`](#toc-sharedmemory-hash-table-pow-unsigned-integer)
* [`sharedmemory.heap_size`](#toc-sharedmemory-heap-size-unsigned-integer)
* [`sharedmemory.log_level`](#toc-sharedmemory-log-level-unsigned-integer)
* [`suppress_type`](#toc-suppress-type-string)
* [`temp_dir`](#toc-temp-dir-string)
* [`traces`](#toc-traces-integer)

 The following options are deprecated and have been removed in the latest version of Flow:

 * [`strip_root`](#toc-strip-root-boolean)
* [`suppress_comment`](#toc-suppress-comment-regex)
* [`types_first`](#toc-types-first-boolean)
* [`well_formed_exports`](#toc-well-formed-exports-boolean)
* [`esproposal.class_instance_fields`](#toc-esproposal-class-instance-fields-enable-ignore-warn)
* [`esproposal.class_static_fields`](#toc-esproposal-class-static-fields-enable-ignore-warn)
* [`esproposal.decorators`](#toc-esproposal-decorators-ignore-warn)
* [`esproposal.export_star_as`](#toc-esproposal-export-star-as-enable-ignore-warn)
* [`esproposal.optional_chaining`](#toc-esproposal-optional-chaining-enable-ignore-warn)
* [`esproposal.nullish_coalescing`](#toc-esproposal-nullish-coalescing-enable-ignore-warn)

 ### 
`all` *`(boolean)`*

 Set this to `true` to check all files, not just those with `@flow`.

 The default value for `all` is `false`.

 ### 
`autoimports` *`(boolean)`* ≥0.143.0

 When enabled, IDE autocomplete suggests the exports of other files, and the necessary `import` statements are automatically inserted. A “quick fix” code action is also provided on undefined variables that suggests matching imports.

 The default value for `autoimports` is `true` as of Flow v0.155.0.

 ### 
`babel_loose_array_spread` *`(boolean)`*

 Set this to `true` to check that array spread syntax is only used with arrays, not arbitrary iterables (such as `Map` or `Set`). This is useful if you transform your code with Babel in [loose mode](https://babeljs.io/docs/en/babel-plugin-transform-spread#loose) which makes this non-spec-compliant assumption at runtime.

 For example:

 
```
const set = new Set();
const values = [...set]; // Valid ES2015, but Set is not compatible with $ReadOnlyArray in Babel loose mode

```
 The default value for `babel_loose_array_spread` is `false`.

 ### 
`emoji` *`(boolean)`*

 Set this to `true` to add emoji to the status messages that Flow outputs when it’s busy checking your project.

 The default value for `emoji` is `false`.

 ### 
`exact_by_default` *`(boolean)`*

 Set this to `true` to indicate that Flow should interpret object types as exact by default. When this flag is `false`, Flow has the following behavior:

 
```
{foo: number} // inexact
{| foo: number |} // exact
{foo: number, ...} // inexact

```
 When this flag is `true`, Flow has the following behavior:

 
```
{foo: number} // exact
{| foo: number |} // exact
{foo: number, ...} // inexact

```
 The default value is `false`.

 ### 
`experimental.const_params` *`(boolean)`*

 Setting this to `true` makes Flow treat all function parameters as const bindings. Reassigning a param is an error which lets Flow be less conservative with refinements.

 The default value is `false`.

 ### 
`inference_mode` *`(classic | constrain_writes)`* ≥0.184.0

 Setting this to `constrain_writes` will enable the constrained-writes inference mode.

 For more info, see the [constrained-writes docs](../lang/constrained-writes).

 The default value is `classic`

 ### 
`include_warnings` *`(boolean)`*

 Setting this to `true` makes Flow commands include warnings in the error output. Warnings are hidden by default in the CLI to avoid console spew. (An IDE is a much better interface to show warnings.)

 The default value is `false`.

 ### 
`lazy_mode` *`(boolean)`*

 For more on lazy modes, see the [lazy modes docs](../lang/lazy-modes).

 Setting `lazy_mode` in the `.flowconfig` will cause new Flow servers for that root to use lazy mode (or no lazy mode if set to `false`). This option can be overridden from the CLI using the `--lazy-mode` flag.

 The default value is `false`.

 ### 
`log.file` *`(string)`*

 The path to the log file (defaults to `/tmp/flow/<escaped root path>.log`).

 ### 
`max_header_tokens` *`(integer)`*

 Flow tries to avoid parsing non-flow files. This means Flow needs to start lexing a file to see if it has `@flow` or `@noflow` in it. This option lets you configure how much of the file Flow lexes before it decides there is no relevant docblock.

 * Neither `@flow` nor `@noflow` - Parse this file with Flow syntax disallowed and do not typecheck it.
* @flow - Parse this file with Flow syntax allowed and typecheck it.
* @noflow - Parse this file with Flow syntax allowed and do not typecheck it. This is meant as an escape hatch to suppress Flow in a file without having to delete all the Flow-specific syntax.

 The default value of `max_header_tokens` is 10.

 ### 
`module.file_ext` *`(string)`*

 By default, Flow will look for files with the extensions `.js`, `.jsx`, `.mjs`, `.cjs` and `.json`. You can override this behavior with this option.

 For example, if you do:

 
```
[options]
module.file_ext=.foo
module.file_ext=.bar
```
 Then Flow will instead look for the file extensions `.foo` and `.bar`.

 
>  **Note:** you can specify `module.file_ext` multiple times
> 
>  

 ### 
`module.ignore_non_literal_requires` *`(boolean)`*

 Set this to `true` and Flow will no longer complain when you use `require()` with something other than a string literal.

 The default value is `false`.

 ### 
`module.name_mapper` *`(regex -> string)`*

 Specify a regular expression to match against module names, and a replacement pattern, separated by a `->`.

 For example:

 
```
module.name_mapper='^image![a-zA-Z0-9$_]+$' -> 'ImageStub'
```
 This makes Flow treat `require('image!foo.jpg')` as if it were `require('ImageStub')`.

 These are [OCaml regular expressions](http://caml.inria.fr/pub/docs/manual-ocaml/libref/Str.html#TYPEregexp). Use `\(` and `\)` (slashes required!) to create a capturing group, which you can refer to in the replacement pattern as `\1` (up to `\9`).

 
>  **Note:** you can specify `module.name_mapper` multiple times
> 
>  

 ### 
`module.name_mapper.extension` *`(string -> string)`*

 Specify a file extension to match, and a replacement module name, separated by a `->`.

 
>  **Note:** This is just shorthand for `module.name_mapper='^\(.*\)\.EXTENSION$' -> 'TEMPLATE'`)
> 
>  

 For example:

 
```
module.name_mapper.extension='css' -> '<PROJECT_ROOT>/CSSFlowStub.js.flow'
```
 Makes Flow treat `require('foo.css')` as if it were `require(PROJECT_ROOT + '/CSSFlowStub')`.

 
>  **Note:** You can specify `module.name_mapper.extension` multiple times for different extensions.
> 
>  

 ### 
`module.system` *`(node|haste)`*

 The module system to use to resolve `import` and `require`. [Haste](https://github.com/facebook/node-haste) is used in React Native.

 The default is `node`.

 ### 
`module.system.node.main_field` *`(string)`*

 Flow reads `package.json` files for the `"name"` and `"main"` fields to figure out the name of the module and which file should be used to provide that module.

 So if Flow sees this in the `.flowconfig`:

 
```
[options]
module.system.node.main_field=foo
module.system.node.main_field=bar
module.system.node.main_field=baz
```
 and then it comes across a `package.json` with

 
```
{
  "name": "kittens",
  "main": "main.js",
  "bar": "bar.js",
  "baz": "baz.js"
}
```
 Flow will use `bar.js` to provide the `"kittens"` module.

 If this option is unspecified, Flow will always use the `"main"` field.

 See [this GitHub issue for the original motivation](https://github.com/facebook/flow/issues/5725)

 ### 
`module.system.node.resolve_dirname` *`(string)`*

 By default, Flow will look in directories named `node_modules` for node modules. You can configure this behavior with this option.

 For example, if you do:

 
```
[options]
module.system.node.resolve_dirname=node_modules
module.system.node.resolve_dirname=custom_node_modules
```
 Then Flow will look in directories named `node_modules` or `custom_node_modules`.

 
>  **Note:** you can specify `module.system.node.resolve_dirname` multiple times
> 
>  

 ### 
`module.use_strict` *`(boolean)`*

 Set this to `true` if you use a transpiler that adds `"use strict";` to the top of every module.

 The default value is `false`.

 ### 
`munge_underscores` *`(boolean)`*

 Set this to `true` to have Flow treat underscore-prefixed class properties and methods as private. This should be used in conjunction with [`jstransform`’s ES6 class transform](https://github.com/facebook/jstransform/blob/master/visitors/es6-class-visitors.js), which enforces the same privacy at runtime.

 The default value is `false`.

 ### 
`no_flowlib` *`(boolean)`*

 Flow has builtin library definitions. Setting this to `true` will tell Flow to ignore the builtin library definitions.

 The default value is `false`.

 ### 
`react.runtime` *`(automatic|classic)`* ≥0.123.0

 Set this to `automatic` if you are using React’s automatic runtime in `@babel/plugin-transform-react-jsx`. Otherwise, use `classic`. [See the babel documentation](https://babeljs.io/docs/en/babel-plugin-transform-react-jsx) for details about the transform.

 The default value is `automatic`.

 ### 
`server.max_workers` *`(integer)`*

 The maximum number of workers the Flow server can start. By default, the server will use all available cores.

 ### 
`sharedmemory.dirs` *`(string)`*

 This affects Linux only.

 Flow’s shared memory lives in a memory mapped file. On more modern versions of Linux (3.17+), there is a system call `memfd_create` which allows Flow to create the file anonymously and only in memory. However, in older kernels, Flow needs to create a file on the file system. Ideally this file lives on a memory-backed tmpfs. This option lets you decide where that file is created.

 By default this option is set to `/dev/shm` and `/tmp`

 
>  **Note:** You can specify `sharedmemory.dirs` multiple times.
> 
>  

 ### 
`sharedmemory.minimum_available` *`(unsigned integer)`*

 This affects Linux only.

 As explained in the [`sharedmemory.dirs`](options) option’s description, Flow needs to create a file on a filesystem for older kernels. `sharedmemory.dirs` specifies a list of locations where the shared memory file can be created. For each location, Flow will check to make sure the filesystem has enough space for the shared memory file. If Flow will likely run out of space, it skips that location and tries the next. This option lets you configure the minimum amount of space needed on a filesystem for shared memory.

 By default it is 536870912 (2^29 bytes, which is half a gigabyte).

 ### 
`sharedmemory.hash_table_pow` *`(unsigned integer)`*

 The 3 largest parts of the shared memory are a dependency table, a hash table, and a heap. While the heap grows and shrinks, the two tables are allocated in full. This option lets you change the size of the hash table.

 Setting this option to X means the table will support up to 2^X elements, which is 16\*2^X bytes.

 By default, this is set to 19 (Table size is 2^19, which is 8 megabytes)

 ### 
`sharedmemory.heap_size` *`(unsigned integer)`*

 This option configures the maximum possible size for the shared heap. You should most likely not need to configure this, as it doesn’t really affect how much RSS Flow uses. However, if you are working on a massive codebase you might see the following error after init: “Heap init size is too close to max heap size; GC will never get triggered!” In this case, you may need to increase the size of the heap.

 By default, this is set to 26843545600 (25 \* 2^30 bytes, which is 25GiB)

 ### 
`sharedmemory.log_level` *`(unsigned integer)`*

 Setting this to 1 will cause Flow to output some stats about the data that is serialized into and deserialized out of shared memory.

 By default this is 0.

 ### 
`suppress_type` *`(string)`*

 This option lets you alias `any` with a given string. This is useful for explaining why you’re using `any`. For example, let’s say you sometimes want to sometimes use `any` to suppress an error and sometimes to mark a TODO. Your code might look like

 
```
var myString: any = 1 + 1;
var myBoolean: any = 1 + 1;
```
 If you add the following to your configuration:

 
```
[options]
suppress_type=$FlowFixMe
suppress_type=$FlowTODO
```
 You can update your code to the more readable:

 
```
var myString: $FlowFixMe = 1 + 1;
var myBoolean: $FlowTODO = 1 + 1;
```
 
>  **Note:** You can specify `suppress_type` multiple times.
> 
>  

 ### 
`temp_dir` *`(string)`*

 Tell Flow which directory to use as a temp directory. Can be overridden with the command line flag `--temp-dir`.

 The default value is `/tmp/flow`.

 ### 
`traces` *`(integer)`*

 Enables traces on all error output (showing additional details about the flow of types through the system), to the depth specified. This can be very expensive, so is disabled by default.

 ### 
`strip_root` *`(boolean)`* ≤0.48

 Obsolete. Set this to `true` to always strip the root directory from file paths in error messages when using `--json`, `--from emacs`, and `--from vim`. Do not use this option. Instead, pass the command line flag `--strip-root`.

 By default this is `false`.

 ### 
`suppress_comment` *`(regex)`* ≤0.126

 Defines a magical comment that suppresses any Flow errors on the following line. For example:

 
```
suppress_comment= \\(.\\|\n\\)*\\$FlowFixMe
```
 will match a comment like this:

 
```
// $FlowFixMe: suppressing this error until we can refactor
var x : string = 123;
```
 and suppress the error. If there is no error on the next line (the suppression is unnecessary), an “Unused suppression” warning will be shown instead.

 If no suppression comments are specified in your config, Flow will apply one default: `// $FlowFixMe`.

 
>  **Note:** You can specify `suppress_comment` multiple times. If you do define any `suppress_comment`s, the built-in `$FlowFixMe` suppression will be erased in favor of the regexps you specify. If you wish to use `$FlowFixMe` with some additional custom suppression comments, you must manually specify `\\(.\\|\n\\)*\\$FlowFixMe` in your custom list of suppressions.
> 
>  

 
>  **Note:** In version v0.127.0, the option to specify the suppression comment syntax was removed. `$FlowFixMe`, `$FlowIssue`, `$FlowExpectedError`, and `$FlowIgnore` became the only standard suppressions.
> 
>  

 ### 
`types_first` *`(boolean)`* ≥0.125.0  ≤0.142

 For more on types-first mode, see the [types-first docs](../lang/types-first).

 Flow builds intermediate artifacts to represent signatures of modules as they are checked. If this option is set to `false`, then these artifacts are built using inferred type information. If this option is set to `true`, then they are built using type annotations at module boundaries.

 The default value for `types_first` is `true` (as of version 0.134).

 ### 
`well_formed_exports` *`(boolean)`* ≥0.125.0  ≤0.142

 Enforce the following restrictions on file exports:

 * Statements manipulating `module.exports` and the `exports` alias may only appear as top-level statements.
* Parts of the source that are visible from a file’s exports need to be annotated unless their type can be trivially inferred (e.g. the exported expression is a numeric literal). This is a requirement for types-first mode to function properly. Failure to properly annotate exports raise `signature-verification-failure`s.

 This option is set to `true` by default, since it is implied by [`types_first`](#toc-types-first-boolean), but the option is useful on its own when upgrading a project from classic mode to types-first mode.

 ### 
`well_formed_exports.includes` *`(string)`* ≥0.128.0  ≤0.142

 Limit the scope of the `well_formed_exports` requirement to a specific directory of this project. For example

 
```
well_formed_exports=true
well_formed_exports.includes=<PROJECT_ROOT>/dirA
well_formed_exports.includes=<PROJECT_ROOT>/dirB
```
 will only report export related errors in files under `dirA` and `dirB`. This option requires `well_formed_exports` to be set to `true`.

 The purpose of this option is to help prepare a codebase for Flow types-first mode. See [this section](#toc-seal-your-intermediate-results) for more.

 Between versions v0.125.0 and v0.127.0, this option was named `well_formed_exports.whitelist`.

 ### 
`esproposal.class_instance_fields` *`(enable|ignore|warn)`* ≤0.148

 Set this to `warn` to indicate that Flow should give a warning on use of instance [class fields](https://github.com/tc39/proposal-class-public-fields) per the pending spec.

 You may also set this to `ignore` to indicate that Flow should simply ignore the syntax (i.e. Flow will not use this syntax to indicate the presence of a property on instances of the class).

 The default value of this option is `enable`, which allows use of this proposed syntax.

 ### 
`esproposal.class_static_fields` *`(enable|ignore|warn)`* ≤0.148

 Set this to `warn` to indicate that Flow should give a warning on use of static [class fields](https://github.com/tc39/proposal-class-public-fields) per the pending spec.

 You may also set this to `ignore` to indicate that Flow should simply ignore the syntax (i.e. Flow will not use this syntax to indicate the presence of a static property on the class).

 The default value of this option is `enable`, which allows use of this proposed syntax.

 ### 
`esproposal.decorators` *`(ignore|warn)`* ≤0.148

 Set this to `ignore` to indicate that Flow should ignore decorators.

 The default value of this option is `warn`, which gives a warning on use since this proposal is still very early-stage.

 ### 
`esproposal.export_star_as` *`(enable|ignore|warn)`* ≤0.148

 Set this to `enable` to indicate that Flow should support the `export * as` syntax from [leebyron’s proposal](https://github.com/leebyron/ecmascript-more-export-from).

 You may also set this to `ignore` to indicate that Flow should simply ignore the syntax. The default value of this option is `warn`, which gives a warning on use since this proposal is still very early-stage.

 ### 
`esproposal.optional_chaining` *`(enable|ignore|warn)`* ≤0.148

 Set this to `enable` to indicate that Flow should support the use of [optional chaining](https://github.com/tc39/proposal-optional-chaining) per the pending spec.

 You may also set this to `ignore` to indicate that Flow should simply ignore the syntax.

 The default value of this option is `warn`, which gives a warning on use since this proposal is still very early-stage.

 ### 
`esproposal.nullish_coalescing` *`(enable|ignore|warn)`* ≤0.148

 Set this to `enable` to indicate that Flow should support the use of [nullish coalescing](https://github.com/tc39/proposal-nullish-coalescing) per the pending spec.

 You may also set this to `ignore` to indicate that Flow should simply ignore the syntax.

 The default value of this option is `warn`, which gives a warning on use since this proposal is still very early-stage.



 © 2013–present Facebook Inc.  
Licensed under the MIT License.  

<https://flow.org/en/docs/config/options>

flow