开始使用 flow
-
安装 flow 环境
yarn add -D flow-bin yarn flow init yarn flow start
-
代码块
// @flow function sum(a: number, b: number) { return a + b; } sum('1', '2');
-
删除类型注解才能运行
-
方法一
# 安装删除注解模块到本地 yarn add --dev flow-remove-types # 执行删除注解命令 yarn flow-remove-types ./ -d dist
-
方法二
yarn add @babel/cli @babel/core @babel/preset-flow
添加 .babelrc 文件到项目根目录
{ "presets": ["@babel/preset-flow"] }
执行 babel 转码命令
yarn babel src -d dist
Flow 开发工具插件
flow language surpport
Flow 类型推断
// @flow
function square(n: number) {
return Math.pow(n, 2);
}
// square('100');
square(100);
Flow 类型注解
// @flow
function square(n: number): number {
return Math.pow(n, 2);
}
let num: number = 100;
function foo(): number {
return 2;
}
function bar(): void {}
原始类型
// @flow
const a: string = 'foobar';
const b: number = Infinity; // 100 NaN
const c: boolean = false; // true
const d: null = null;
const e: void = undefined; // 特殊的约定
const f: symbol = Symbol();
数组类型
// @flow
const arr1: Array<number> = [1, 2, 3];
const arr2: number[] = [1, 2, 3];
// 元组
const foo: [string, number] = ['foo', 5];
对象类型
// @flow
const obj1: { foo: string, bar: number } = { foo: 'foo', bar: 1 };
const obj2: { foo?: string, bar: number } = { bar: 2 };
const obj3: { [string]: string } = {};
obj3.k1 = 'v1';
obj3.k2 = 'v2';
函数类型
// @flow
function foo(callback: (string, number) => void) {
callback('string', 100);
}
foo(function( str, n)) {}
其他类型
// @flow
const a: 'foo' = 'foo'; // 字面量类型
// 配合联合类型使用
const type: 'success' | 'warning' | 'danger' = 'success';
const b: string | number = '100';
// 使用 type 关键字声明类型
type StringOrNumber = string | number;
const c: StringOrNumber = 'string or number';
const gender: ?number = null; // maybe
const vender: ?number = undefined; // maybe