flow用来对js进行静态类型检查,检查分为:
类型注释: 事先注释好我们期待的类型, Flow 会基于这些注释来判断
类型推断: 通过变量的使用上下文来推断出变量类型, 然后根据这些推断来检查类型
function函数类有两个地方用到了类型,参数输入的时候和return返回数据的时候,下面规定了参数必须是string类型,返回值也是string类型,所以后面一条报错。
// @flow
function concat(a: string, b: string): string {
return a + b;
}
concat("foo", "bar"); // Works!
// $ExpectError
concat(true, false); // Error!
当省略注释的时候,就使用类型推断。
// @flow
function concat(a, b) {
return a + b;//+ 可以是数字类型的相加,也可以是字符串连接
}
concat("foo", "bar"); // Works!
concat(1, 2); // Works!
函数的参数使用注释的情况:
1、函数声明
function method(str, bool, ...nums) {//省略注释
// ...
}
function method(str: string, bool?: boolean, ...nums: Array<number>): void {//有注释的
// ...
}
2、箭头函数
let method = (str, bool, ...nums) => {//无注释
// ...
};
let method = (str: string, bool?: boolean, ...nums: Array<number>): void => {//无注释
// ...
};
str: string--正常带注释写法
bool?: boolean,--该参数为可选的,用?标记,能接受省略,undefined,或者其他匹配的值(这里为boolean类型),但是不接受null。
bool: ?boolean,表示可以为boolean或者null。:?T表示可以是null,或者规定的Type
// @flow
function method(optionalValue?: string) {
// ...
}
method(); // Works.省略
method(undefined); // Works.undefined
method("string"); // Works.规定的类型
// $ExpectError
method(null); // Error!
...nums: Array<number>--剩余参数,类型为Array,每一项都为number类型,实际意思就是,传入的参数得是number类型的,所有的参数组成的这个剩余参数就变成了一个值number的数组。
// @flow
function method(...args: Array<number>) {
// ...
}
method(); // Works.
method(1); // Works.
method(1, 2); // Works.
method(1, 2, 3); // Works.
异步(async)函数需要返回一个promise
// @flow
async function method(): Promise<number> {
return 123;
}
this返回的是函数调用call的那个上下文
function method() {
return this;
}
var num: number = method.call(42);
// $ExpectError
var str: string = method.call(42);
predict function 推断函数?
function truthy(a, b): boolean {
return a && b; // a为真,返回b,a为假,返回a,所以返回值不一定是Boolean
}
function concat(a: ?string, b: ?string): string {
if (truthy(a, b)) {
// $ExpectError
return a + b;
}
return '';
}
关于%check的使用,没看懂
function isString(y): %checks {
return typeof y === "string";
}