注释类型
Flow 支持基于注释的语法,这使得无需编译文件即可使用 Flow。
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"]});
13:33-13:40: Cannot call `method` with object literal bound to `value` because array literal [1] is incompatible with string [2] in property `baz`. [incompatible-call]
这些注释允许 Flow 在普通 JavaScript 文件中工作,无需任何额外操作。
注释类型语法
语法主要包含两个部分:类型包含和类型注解。
类型包含注释
如果希望 Flow 将注释视为普通语法,可以在注释开头添加双冒号 ::
。
1/*::2type MyAlias = {3 foo: number,4 bar: boolean,5 baz: string,6};7*/8
9class MyClass {10 /*:: prop: string; */11}
这将代码包含到 Flow 所见的语法中。
1type MyAlias = {2 foo: number,3 bar: boolean,4 baz: string,5};6
7class MyClass {8 prop: string;9}
但 JavaScript 会忽略这些注释,因此您的代码是有效的 JavaScript 语法。
1class MyClass {2
3}
此语法也以 flow-include
形式提供。
1/*flow-include2type MyAlias = {3 foo: number,4 bar: boolean,5 baz: string,6};7*/8
9class MyClass {10 /*flow-include prop: string; */11}
类型注解注释
无需每次都键入完整的包含,也可以使用类型注解简写,在注释开头使用单个冒号 :
。
1function method(param /*: string */) /*: number */ {2 return 1;3}
这与在包含注释中包含类型注解相同。
1function method(param /*:: : string */) /*:: : number */ {2 return 1;3}
注意:如果要使用可选函数参数,则需要使用包含注释形式。
特别感谢:Jarno Rantanen 为构建 flotate 并支持我们将他的语法合并到 Flow 中而付出的努力。