Flow类型检查器快速上手
# .
# Flow概述
Flow JavaScript的类型检查器
Flow是JavaScript代码的静态类型检查器。它可以帮助您提高工作效率。让您的代码更快,更智能,更自信,更大规模。
# 开始-命令行工具的使用
安装flow
npm i flow-bin -D
1
安装Bable
npm i -S babel-cli
npm i -S babel-preset-flow
1
2
2
配置package.json:
package.json中的scripts执行flow命令, 转换src/目录下的js代码, 并且输出到lib/目录下
···
"scripts": {
"flow": "flow",
"init": "flow init",
"build": "babel src/ -d lib/"
}
···
1
2
3
4
5
6
7
2
3
4
5
6
7
新建 .babelrc
文件,babel的配置文件
{
"presets": [
"flow"
]
}
1
2
3
4
5
2
3
4
5
执行初始化命令,执行完会产生一个 .flowconfig
文件,配置那需要转换的
npm run init
1
使用npm执行flow命令
npm run flow
or
npm run flow --help
1
2
3
2
3
# flow使用
给你的 js
文件第一行添加 // @flow
标记,flow进程才会对该文件进行类型检查
懒人命令,所有文件检测:
npm run flow check --all
1
// @flow
function sum(a: number, b: number):number {// function sum():number{} 返回number类型的值
return a + b;
}
let val = sum(100, '100')
console.log(val);
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
运行flow后
npm run flow
> flow@1.0.0 flow
> flow
Error ---------------------------------------------------------------------------------------------- src/01-demo.js:7:20
Cannot call `sum` with `'100'` bound to `b` because string [1] is incompatible with number [2]. [incompatible-call]
src/01-demo.js:7:20
7| let val = sum(100, '100')
^^^^^ [1]
References:
src/01-demo.js:3:28
3| function sum(a: number, b: number):number {
^^^^^^ [2]
Found 1 error
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# VSCode Flow插件 or IDE插件 (推荐)
名称:Flow Language Support
# flow中的类型
类型 | 说明 |
---|---|
number | 数字、NaN、Infinity都是number类型的数据 |
string | 字符串 |
string | 字符串 |
null | 只有null是null类型的 |
void | undefined在flow中的类型就是void |
Array | 数组类型,定义的时候需要使用Array这种形式, T为指定的类型,说的是特定类型的数据组成的数组 |
Object | 对象类型,由于对象比较自由,所以规定对象类型的时候有多种写法 |
any | 表示任意类型,这个类型尽量少用,但有时又很有用! |
Functions | 函数类型 |
Maybe | Maybe类型允许我们声明一个包含null和undefined两个潜在类型的值。 |
或操作 | 或操作可以设置一个变量为多种可能的类型 类型1 |
类型推断 | flow会尝试自行推断某个数据的类型 |
# Flow具体详情使用教程点击我 (opens new window)
编辑 (opens new window)
上次更新: 2023/05/18, 07:05:54