Flow 静态类型检测工具
产生的原因:JavaScript 没有类型检查
- 安装flow语法插件
字面量类型
- let monthsAYear: 12 = 12;
- monthsAYear = 13; // Flow 会在这里报错
- 字面量值也可以作为一种类型,符合这种类型的变量只有这个字面量本身;给这个变量赋其他值, Flow 在进行类型检测时都会报错;
基本类型的类型标注语法
- JavaScript 中的基本类型,类型标注语法是在变量后加上一个冒号,空格,然后是相应的类型名称,如:
// @flow
const a: string = 'zhihu';
const b: number = 5;
const c: boolean = false;
const d: void = undefined;
const e: null = null; - 以上需要注意的几点:
- undefined 的类型是 void;
- null 的类型是 null;
- string 类型、number 类型和 boolean 类型,其类型名称都是小写开头;但是在 JS 中还有相对应的大写开头的类型名称,如 String,Number, Boolean;
元组 tuple
- 在 JS 里,元组就是数组来表示的,并且是一个有限数组,数组每一项的类型分别标注出来
const recordItem : [number, string, boolean] = [1, 'First', true];
对象类型的标注
-
const borderConfig : { width: number, color: string, hasShadow: boolean } = { width: 10, color: 'red', hasShadow: true, } -
`type BorderConfigType = {
width: number,
color: string,
hasShadow: boolean
}
const borderConfig : BorderConfigType = {
width: 10,
color: 'red',
hasShadow: true,
}
`
type 是 Flow 中的关键字,用来定义自定义的类型,并且可以在后面的类型标注中使用
类的标注
- 类中用到的属性必须额外添加类型标注,并且是在与方法同一个层级
class RightClass { props: number; //就像这样。 method(){ this.props = 1; } }
联结类型(Union Type)的使用
// @flow type C = A | B;
如果是定义函数的参数是一个联结类型,需要在函数的内部针对每种类型都作出判断并进行相应处理;这个过程称为类型的细化(Type Refinement)。
// @flow type MsgType = string | number; function show(msg: MsgType) { if (typeof msg === 'string' ){ // do something } else { // 在这个代码块里,可以放心将参数 msg 当成数字类型 // Flow 也会作出这样的推理 } }
交叉类型(Intersection Type)的使用
// @flow type C = A & B;- 必须满足交叉类型的约束
对象的可选属性与变量的可选类型
// @flow type Test = { key1: ?string, // 属性值不一定的 string,还可以是 null 或者 undefined; key2?: number, // key2 可选,类型一定是number }
浙公网安备 33010602011771号