Skip to main content

注释类型

Flow 支持基于注释的语法,这使得无需编译文件即可使用 Flow。

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

1/*::2type MyAlias = {3  foo: number,4  bar: boolean,5  baz: string,6};7*/8
9function method(value /*: MyAlias */) /*: boolean */ {10  return value.bar;11}12
13method({foo: 1, bar: true, baz: ["oops"]});

这些注释允许 Flow 在纯 JavaScript 文件中工作,无需任何额外的工作。

¥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.

输入包含注释

¥Type include comments

如果你想让 Flow 将注释视为正常语法,你可以通过在注释开头添加双冒号 :: 来实现:

¥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/*::2type MyAlias = {3  foo: number,4  bar: boolean,5  baz: string,6};7*/8
9class MyClass {10  /*:: prop: string; */11}

这将代码包含到 Flow 看到的语法中:

¥This includes the code into the syntax that Flow sees:

1type MyAlias = {2  foo: number,3  bar: boolean,4  baz: string,5};6
7class MyClass {8  prop: string;9}

但 JavaScript 会忽略这些注释,因此你的代码是有效的 JavaScript 语法:

¥But JavaScript ignores these comments, so your code is valid JavaScript syntax:

1class MyClass {2
3}

此语法也以 flow-include 形式提供:

¥This syntax is also available in a flow-include form:

1/*flow-include2type MyAlias = {3  foo: number,4  bar: boolean,5  baz: string,6};7*/8
9class MyClass {10  /*flow-include prop: string; */11}

输入注释注释

¥Type annotation comments

你还可以使用类型注释简写,并在注释开头添加一个冒号 :,而不是每次都键入完整的包含内容。

¥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.

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

这与在包含注释中包含类型注释相同。

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

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

注意:如果你想使用可选的函数参数,你需要使用包含注释表单。

¥Note: If you want to use optional function parameters you'll need to use the include comment form.


特别感谢:亚诺·兰塔宁 构建了 漂浮 并支持我们将他的语法上游合并到 Flow 中。

¥Special thanks to: Jarno Rantanen for building flotate and supporting us merging his syntax upstream into Flow.