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 來源:簡書 著做權歸做者全部。商業轉載請聯繫做者得到受權,非商業轉載請註明出處。
相關文章
相關標籤/搜索