# flow
yarn add --dev @babel/core @babel/cli @babel/preset-flow
# 创建.babelrc
{
"presets": ["@babel/preset-flow"]
}
创建一个src目录,把代码放入,然后配置package.json
{
"name": "my-project",
"main": "lib/index.js",
"scripts": {
"build": "babel src/ -d lib/",
"prepublish": "yarn run build"
}
}
# 安装flow
yarn add --dev flow-bin
运行flow
yarn run flow
$ flow
No errors!
Done in 0.95s.
需要加上/*@flow*/进行处理需要使用flow的代码;flow代码的两种检查类型的方式
- 类型判断
/*@flow*/
function split(str) {
return str.split(' ')
}
split(11)
Error ---------------------------------------------- src/index.js:4:10
Cannot call `str.split` because property `split` is missing in `Number` [1].
src/index.js:4:10
4| return str.split(' ')
^^^^^^^^^^^^^^
References:
src/index.js:7:7
7| split(11)
^^ [1]
- 类型注释
/*@flow*/
function add(x: number, y: number): number {
return x + y
}
add('Hello', 11)
Cannot call `add` with `'Hello'` bound to `x` because string [1] is incompatible with number [2].
src/index.js:7:5
7| add('Hello', 11)
^^^^^^^ [1]
References:
src/index.js:3:17
3| function add(x: number, y: number): number {
^^^^^^ [2]
数组定义
/*@flow*/
var arr: Array<number> = [1, 2, 3]
arr.push('Hello')//报错,不是数字
类和对象
/*@flow*/
class Bar {
x: string; // x 是字符串
y: string | number; // y 可以是字符串或者数字
z: boolean;
constructor(x: string, y: string | number) {
this.x = x
this.y = y
this.z = false
}
}
var bar: Bar = new Bar('hello', 4)
var obj: { a: string, b: number, c: Array<string>, d: Bar } = {
a: 'hello',
b: 11,
c: ['hello', 'world'],
d: new Bar('hello', 3)
}
null 若想任意类型 T 可以为 null 或者 undefined,只需类似如下写成 ?T 的格式即可。
/*@flow*/
var foo: ?string = null
此时,foo 可以为字符串,也可以为 null。
← TortoiseGit 虚拟机 →