类型检测器 FLOW

在很多大型前端框架、插件中都有使用到flow去做类型检测的(react、vue、core)。

安装flow

yarn add flow-bin -dev

 运行时直接使用

yarn flow

会报错提示

 执行flow init可能会报错

解决方法:

  • 1.Windows PowerShell.并以管理员身份运行
  • 2. 输入 set-ExecutionPolicy RemoteSigned 回车
  • 3. 输入 A 回车
  • 4.再输入get-ExecutionPolicy,回车 出现RemoteSigned 即为成功

 如果以上无效的话直接创建.flowconfig文件

.flowconfig文件配置参考链接

现在文件顶部有

// @flow
/* @flow */

的文件就会在执行yarn flow的时候被检验

flow的检验会和vscode的JavaScript校验冲突,需要将其设置为false

“javascript.validate.enable”: false

移除注解

这个注解是在编译的时候去判断类型,生产的时候不需要,

有两种方法:

  1. 安装flow-remove-types, 执行 yarn flow-remove-types src -d dist
  2. 使用babel, yarn add @babel/core @babel/cli (在命令行里使用babel) @babel/preset-flow 
    1. 创建.babelrc文件,{"presets":"@/babel/preset-flow"}
    2. 执行 yarn babel src -d dist

命令执行检测太过于麻烦,可以直接安装flow插件来在代码中直接提示

类型检测器 FLOW_第1张图片

flow类型推断

// @flow
// 没有给出类型会推断需要number类型,给的string会报错
function square(n) {
    return n * n
}
square('2')

类型注释: 

// @flow
function add(num: number, num1: number) {
  return num + num1
}
let num: number = 100;
function a(): number {
  return 1
}
function bb(): void {
}

flow的原始类型

const s:string = '1234'
const numb: number = 1234
const b: boolean = true
const d:null = null
const f:void = undefined
const ff: symbol = Symbol()

 flow 数组类型和元组

const list :Array = [1,2,3]
const numberArray :number[] = [1,2,3]
// 元组
const arr :[number, string] = [1,'2']

flow对象类型

const obj : {age?: number, name: string} = {age:10, name:'张三'}
const obj1 : {[string]: number} = {}

 flow 函数类型

function f(callback: (string,number)=> void) {
    callback('123', 123)
}
f(function(str,num) {})

flow 特殊类型

// 只能是这个值
const a: 'foo' = 'foo'
const b : 'big' | 'small' | 'middle' = 'big'
const c: string | nmuber = 10
// 表示可以是null 和undefined
const d: ?number = undefined
const f: number|null|void = undefined

 flow 任意类型 mixed和any

function mixedFun(value: mixed) {
  if (typeof value === string) {
    value.substr(1)
  }
  if (typeof value === number) {
    value = value * value
  }
}
mixedFun('123')
mixedFun(123)
function mixedFun1(value: any) {
  value.substr(1)
  value = value * value
}
mixedFun1(123)
mixedFun1('123')

flow官网类型详细说明

flow第三方type整理

flow的其他类型成员

类型检测器 FLOW_第2张图片

你可能感兴趣的:(typescript,javascript,typescript)