Comment Types

Flow with plain JavaScript code by using a special comment syntax

Flow supports a comment-based syntax, which makes it possible to use Flow without having to compile your files.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// @flow

/*::
type MyAlias = {
  foo: number,
  bar: boolean,
  baz: string,
};
*/

function method(value /*: MyAlias */) /*: boolean */ {
  return value.bar;
}

method({ foo: 1, bar: true, baz: ["oops"] });
object literal This type is incompatible with the expected param type of object type

These comments allows 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.

1
2
3
4
5
6
7
8
9
10
11
/*::
type Foo = {
  foo: number,
  bar: boolean,
  baz: string
};
*/

class MyClass {
  /*:: prop: string; */
}

This includes the code into the syntax that Flow sees.

1
2
3
4
5
6
7
8
9
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.

1
2
3
class MyClass {

}

This syntax is also available in a flow-include form.

1
2
3
4
5
6
7
8
9
10
11
/*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.

1
2
3
function method(param /*: string */) /*: number */ {
  // ...
}

This would be the same as including a type annotation inside an include comment.

1
2
3
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 for building flotate and supporting us merging his syntax upstream into Flow.