为什么用Flow

Flow 是 facebook 出品的 JavaScript 静态类型检查工具。Vue.js 的源码利用了 Flow 做了静态类型检查,所以了解 Flow 有助于我们阅读源码。

flow的工作方式?

通常类型检查分成 2 种方式:

安装flow

npm install -g flow-bin

flow init

类型推断:通过变量的使用上下文来推断出变量类型,然后根据这些推断来检查类型。

 

unction split(str) {

 

  return str.split(' ')

 

}

 

split(11)

 

类型注释:事先注释好我们期待的类型,Flow 会基于这些注释来判断

/*@flow*/

function add(x:number, y:number): number {

  return x + y

}

add('Hello', 11)

 

数组-----------------------------

/*@flow*/

var arr: Array<number> = [1, 2, 3]

arr.push('Hello')

 

类和对象--------------------

/*@flow*/

class Bar {

  x: string;           // x 是字符串

  y: string | number | void;  // y 可以是字符串或者数字

  z: boolean;

  constructor(x: string, y: string | number | void) {

    this.x = x

    this.y = y

    this.z = false

  }

}

 

var bar: Bar = new Bar('hello', 4)

var bar: Bar = new Bar('hello')

原文地址:https://www.cnblogs.com/sklhtml/p/9660869.html