Flow入门初识

Flow是facebook出品的JavaScript静态类型检查工具。
因为JavaScript是动态类型语言,它的灵活性也会形成一些代码隐患,使用Flow能够在编译期尽早发现由类型错误引发的bug,这种方式很是有利于大型项目源码的开发和维护,php

1.Flow工做方式

类型推断:经过变量的使用上下文来推断,而后根据这些推断来判断类型。
类型注释:事先注释数据类型,Flow会基于注释来判断。vue

2.Flow安装

$mkdir flowtest
$npm install --g flow-bin
$flow init //初始化,建立一个.flowconfig文档 $flow 

3.使用

// @flow function square(n: number): number { return n * n; } square("2"); // Error! 
$flow
 
 

(1)原始数据类型npm

// @flow function concat(a: string, b: string) { return a + b; } concat("1", 2); // Error! 
// @flow function method(x: number, y: string, z: boolean) { // ... } method(3.14, "hello", true);//No errors! 
// @flow function method(x: Number, y: String, z: Boolean) { // ... } method(new Number("111"), new String("world"), new Boolean(false));//No errors! 

(2)类和对象
Objectbash

// @flow var obj1: { foo: boolean } = { foo: true }; var obj2: { foo: number, bar: boolean, baz: string, } = { foo: 1, bar: true, baz: 'three', };//No errors! 
//@flow 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) } //No errors! 

Array工具

//@flow let arr: Array<number> = [1, 2, 3]; 

(3)自定义类型
Flow 提出了一个 libdef 的概念,能够用来识别这些第三方库或者是自定义类型。例如vuejs的对flow的使用。vue源码下flow文件夹。ui

做者:藕藕藕汀 连接:https://www.jianshu.com/p/197d8912b50d 来源:简书 著做权归做者全部。商业转载请联系做者得到受权,非商业转载请注明出处。
相关文章
相关标签/搜索