Flow入门初识

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

1.Flow工作方式

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

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)原始数据类型

// @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)类和对象
Object

// @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文件夹。



作者:藕藕藕汀
链接:https://www.jianshu.com/p/197d8912b50d
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

posted on 2019-11-30 20:58  漫思  阅读(727)  评论(0编辑  收藏  举报

导航