NoteDeep
FLOW IS A STATIC TYPECHECKER FOR JAVASCRIPT.
静态类型检查

Flow 是一个静态类型检测工具;在现有项目中加上类型标注后,可以在代码阶段就检测出对变量的不恰当使用。Flow 弥补了 JavaScript 天生的类型系统缺陷。利用 Flow 进行类型检查,可以使你的项目代码更加健壮,确保项目的其他参与者也可以写出规范的代码;而 Flow 的使用更是方便渐进式的给项目加上严格的类型检测。那么这么好的 Flow,要怎么开始使用呢?

如何对一个文件进行类型检查?

如果你想对一个文件进行类型检查,必须在文件头部加上一行注释;

// @flow // 或者下面这种 /* @flow */
意思简单明了,AT 一下 Flow 检查器,意思是:“嘿, Flow,来验一下我”。


你一定注意到了,这样改写 JavaScript 代码之后,这段代码是不符合 ECMA 语法规范的;所以在上线时,需要用插件把 Flow 的标注内容去掉;Flow 提供 flow-remove-types 和 babel 插件 两种方式来去除标注内容,感兴趣的话可以点击相应链接,本文不详述。

WebStorm里面,需要把languages 设置为 Javascripts => flow



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!



参考文献:
https://zhuanlan.zhihu.com/p/26204569

评论列表

    如何对一个文件进行类型检查?
    Maybe types
    Optional object properties
    Optional function parameters 可选的函数参数