定义
Flow是facebook出品的JavaScript静态类型检查工具
安装
1、全局安装npm install --g flow-bin 项目目录安装 npm install -D flow-bin
2、npm init -y(-y默认全部yes快速创建) 创建package.json文件,在文件中的scripts中添加:
"scripts": {
"flow": "flow"
}
使用命令
- npm run flow init 在项目文件夹的根目录创建一个.flowconfig文件
- npm run flow check 对所有文件夹进行类型检查
- npm run flow 启动Flow服务(只检查变化部分)
- flow 执行Flow检查
- npm run flow stop 停止Flow服务
- 在被检查的文件最顶部添加 @flow 标识的注释对该文件进行检查
Flow中的数据类型
- number类型可以赋值的类型:number , NaN, Infinity
let a: number = NaN
- string类型
- boolean类型
- void类型: 就是js中的undefined
- null
- Array类型
let arr: Array<number> = []
, 需要指定array的元素类型 - any类型,
let test: any = 任意数据
- interface类型
- 类型推断
函数类型
// @flow
const sum = (arr: Array<number>): number => {
let result = 0;
arr.forEach(item => {
result += item;
});
return result;
};
// 当声明一个函数变量时, 说明这个变量是函数, 参数两个为数字, 返回值为数字
let temp = (a: number, b:number) => number;
// 最常见的ajax, 参数是函数时, 同时箭头后面代表返回值类型,// 不写默认是undefined
const ajax = (callback: (data: Object) => void) {
}
Maybe类型
// 问号代表可以是null或者undefined, 函数没有声明返回值, 即返回值也可以是undefined
// @ flow
const test = (a: ?number) {
console.log(a)
}
或操作
// 就是或操作, 两者类型选择一个
// @flow
let a = number|string = 10;
a = 'abc'
对象类型
// @flow
const ajax = (option: { url:string, type: string, success:(data: Object) => void }) {
}
ajax()// 报错, 因为函数参数是对象
文字类型
function foo(value: 2) {}
foo(2); // Work!
foo(3); // Error!
foo('2'); // Error!
混合类型mixed(使用前需判断类型)
// @flow
function stringify(value: mixed) {
if (typeof value === 'string') {
return "" + value; // Works!
} else {
return "";
}
}
stringify("foo");
接口类型interface(implements是实施、实现, extends是继承)
// @flow
interface Serializable {
serialize(): string;
}
class Foo implements Serializable {
serialize() { return '[Foo]'; } // Works!
}
class Bar implements Serializable {
// $ExpectError
serialize() { return 42; } // Error!
}
类型推断
/*@flow*/
function foo(x) {
return x.split(' ');
}
foo(34);//错误 推断类型为字符串