一:Flow初识
Flow是Facebook出品的JavaScript静态类型检查工具,Vue2.x源码利用了Flow做静态类型检查。
二:Flow工作方式
-
类型推断:根据变量的使用上下文来推断出变量的数据类型从而进行类型检查
function join(x) { return x.join(','); } join(1);
报错Cannot call
x.join
because propertyjoin
is missing inNumber
[1]. [prop-missing]
join是数组的方法,这里需要x
是一个Array
类型,而我们输入的是Number
类型function add(x, y) { return x + y; } add('hello', 2);
这是一个加法运算,我们需要
x
和y
都是Number
类型,如果使用类型推断来进行检查的话我们输入String
也不会报错,因为String
类型也支持+
拼接,所以这个时候就需要使用类型注释
-
类型注释:事先注释好我们需要的类型,Flow根据这些注释来进行类型检查
function add(x:number, y:number) { return x + y; } add('hello', 2);
报错Cannot call
add
with'1'
bound tox
because string [1] is incompatible with number [2]. [incompatible-call]//检查基本类型 function test(x:string,y:boolean){ return y?x:'test'; } test('a',false) //检查数组类型 var arr:Array<number | string>=[1,2,3];//`|`表示`或`,可以同时支持多种类型 arr.push(true) //检查类和对象类型 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类型 //表示支持`string`和`null`或者`undefined`类型 var foo: ?string = null //也可以写成 var foo: ?string = undefined
三:使用Flow
-
安装Flow
安装命令:
npm i flow-bin -g
-
初始化Flow配置文件
.flowconfig
初始化命令:
flow init
-
使用Flow运行检查
运行命令:
flow index.js
(index.js为需要检查的文件) -
自定义检查类型或者关联第三方库类型
在
.flowconfig
文件中修改[libs]
目录为自己需要关联或者自己定义的类型文件目录即可