项目网址:https://gitee.com/big-right-right/flow_-a_-static_-type_-checker_-for_-java-script
## 介绍
Flow (一个 JavaScript 静态类型检测器)
## Flow开发工具插件 (Flow Language Support)
在vscode中安装插件 Flow Language Support,则不符合类型检查的代码都会被标记出来
## 安装和检查
1. 通过如下步骤安装 flow-bin:
执行 cnpm install flow-bin --save-dev
2. 通过如下步骤在项目根目录下添加一个 .flowconfig 文件:
执行 yarn flow init
.flowconfig 文件内容如下:
[ignore]
[include]
[libs]
[lints]
[options]
[strict]
3. 在源代码文件夹src下,在需要进行静态类型检测的文件首行,添加 // @flow
4. 通过如下步骤对文件进行静态类型检查:
执行 yarn flow
此时会看到控制台,输出了类型检查错误。
## 移除源代码中的类型标记
由于带上flow类型检查标记的文件,不是纯正的js文件,无法正常执行,所以需要移除源代码中的类型标记。
### 用 flow-remove-types 移除源码中的flow类型标记
1. 通过如下步骤安装 flow-remove-types:
执行 cnpm install flow-remove-types --save-dev
2. 通过如下步骤把源码编译为无标记的代码:
执行 yarn flow-remove-types src -d dist
此时,就会在目标代码文件夹dist中,发现已经移除了类型标记的代码文件。
### 用 babel 移除源码中的flow类型标记
1. 通过如下步骤安装 babel:
执行 cnpm install @babel/core @babel/cli @babel/preset-flow --save-dev
2. 在项目根目录下添加babel的配置文件 .babelrc
.babelrc文件内容如下:
{
"presets": ["@babel/preset-flow"]
}
3. 通过如下步骤把源码编译为无标记的代码:
执行 yarn babel src -d dist2
## Flow类型参考
1.Flow官网类型描述文档
2.第三方的类型手册:
https://www.saltycrane.com/cheat-sheets/flow-type/latest
## Flow使用代码示例
// @flow
function sum(a: number , b: number){
return a + b
}
sum(1, 2)
sum(1, '2') // flow报语法错误
// Flow原始类型
const a: string = 'ab'
const b: number = NaN // Infinity // 10
const c: boolean = true
const d: null = null
const e: void = undefined
const f: symbol = Symbol('foo')
// Flow数组类型
const arr1: Array<number> = [1, 3, 4]
const arr2: number[] = [1, 2]
// 固定元素个数的数组 叫元组
const foo: [string, number] = ['foo', 100]
// Flow对象类型
const obj1: { foo: string, bar?: number} = {
foo: 'foo',
bar: 200
}
const obj3: { [string]: string } = {}
obj3.key1 = 'value1'
obj3.key2 = '100'
// Flow函数类型
function f1(callback: (string, number) => void){
callback('string', 100)
}
f1(function(str, n){
return undefined
})
// Flow特殊类型
const a: 'foo' = 'foo'
const type: 'success' | 'warning' | 'danger' = 'success'
type StringOrNumber = string | number
const b: string | number = 100
const c: StringOrNumber = 'str1'
// 注解的类型前面加 ? 还允许null 和 undefined
let gender: ?number = undefined
gender = null
gender = 1
// Flow mixed 和 any类型
// mixed - 任何类型都可以 是强类型
// any - 任何类型都可以 是弱类型(允许随意的隐式类型转换)
// any要少用 主要为了兼容老代码
function passMixed(value: mixed){
if(typeof value === 'string'){
value.substr(1)
}
if(typeof value === 'number'){
value * value
}
}
passMixed(10)
passMixed('str')
function passAny(value: any){
value.substr(1)
value * value
}
passAny(null)
passAny(true)
// Flow 类型推断
function square(n){
return n * n
}
square('100') // flow报语法错误
// Flow 类型注解
let num: number = 100
num = '10' // flow报语法错误
function foo(): number {
return 'a' // flow报语法错误
}
// Flow对运行环境提供的API的支持
document.getElementById('ab')
document.getElementById(100) // flow报语法错误
const element: HTMLElement | null = document.getElementById('ab')
本文 完。