欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

什么是Flow

程序员文章站 2022-03-22 23:40:22
...

Flow 概述

JS的类型检测器
什么是Flow
编码阶段就可以知道是否错误。

Flow 快速上手

安装 yarn add flow-bin --dev
记得关闭JS的语法检查,不然报错
什么是Flow
然后再 yarn flow init 不然会找不到执行文件
小插曲,执行yarn flow的时候报错了。原因是路径中文名,换成英文的就可以了。

总结

快速上手:
安装flow: yarn add flow-bin --dev
文件顶部添加注释标记: @flow
添加flow配置文件: yarn flow init
执行flow命令检对应文件: yarn flow
停止flow后台任务: yarn flow stop
编译移除注解
flow工具

Flow 编译移除注解

因为 node运行的话会报错,在运行的时候需要移除注解。不然报错。
安装flow提供的工具: yarn add flow-remove-types --dev
执行命令: yarn flow-remove-types . -d dist

2使用babel

安装babel提供的工具: yarn add @babel/core @babel/cli @babel/preset-flow
添加配置文件.babelrc {“presets”: ["@babel:preset-flow"]}
执行命令 yarn babel src -d dist 在dist中找到编译后的js文件
自动被移除了

什么是Flow

Flow 开发工具插件

VScode插件商店 搜索 Flow Language Support 安装即可,保存之后才会重新检查。
什么是Flow

Flow 类型推断

可以自动判断类型。
什么是Flow

Flow 类型注解

变量和返回值也可以,没有返回值可以用 void代替

什么是Flow

Flow 原始类型

/**
 * 原始类型
 *
 * @flow
 */

const a: string = 'foobar'

const b: number = Infinity // NaN // 100

const c: boolean = false // true

const d: null = null

const e: void = undefined  //undefined用void表示

const f: symbol = Symbol()

Flow 数组类型

/**
 * 数组类型
 *
 * @flow
 */

const arr1: Array<number> = [1, 2, 3]

const arr2: number[] = [1, 2, 3]

// 元组
const foo: [string, number] = ['foo', 100]

Flow 对象类型

/**
 * 对象类型
 *
 * @flow
 */

const obj1: { foo: string, bar: number } = { foo: 'string', bar: 100 }

const obj2: { foo?: string, bar: number } = { bar: 100 }

const obj3: { [string]: string } = {}

obj3.key1 = 'value1'
obj3.key2 = 'value2'


Flow 函数类型

/**
 * 函数类型
 *
 * @flow
 */

function foo (callback: (string, number) => void) {
  callback('string', 100)
}

foo(function (str, n) {
  // str => string
  // n => number
})

Flow 特殊类型

字面量声明,除了你声明的类型外,都不能赋值。

/**
 * 特殊类型
 *
 * @flow
 */

// 字面量类型

const a: 'foo' = 'foo'

const type: 'success' | 'warning' | 'danger' = 'success'

// ------------------------

// 声明类型

type StringOrNumber = string | number

const b: StringOrNumber = 'string' // 100

// ------------------------

// Maybe 类型

const gender: ?number = undefined
// 相当于
// const gender: number | null | void = undefined

Flow Mixed 与 Any

/**
 * Mixed Any
 *
 * @flow
 */

// string | number | boolean | ....
function passMixed (value: mixed) {
  if (typeof value === 'string') {
    value.substr(1)
  }

  if (typeof value === 'number') {
    value * value
  }
}

passMixed('string')

passMixed(100)

// ---------------------------------

function passAny (value: any) {
  value.substr(1)

  value * value
}

passAny('string')

passAny(100)

Flow 运行环境 API

/**
 * 运行环境 API
 *
 * @flow
 */

const element: HTMLElement | null = document.getElementById('app')

什么是Flow

相关标签: ts