6-Flow(01-02-03)

145 阅读2分钟

强类型弱类型

强类型与弱类型

  • 强类型要求实参和形参必须类型一致
  • 弱类型没有类型约束

JavaScript 弱类型产生的问题

  1. 异常需要等到运行时才能发现
  2. 函数功能可能发生改变
  3. 对象索引器的错误用法

静态语言

  • 一个变量声明时它的类型就是明确的,而且声明过后,它的类型就不允许再修改

动态类型

  • 一个变量声明之后,他的类型可以再修改

强类型的优势

  1. 强类型代码错误更早暴露
  2. 强类型代码更智能,编码更准确
  3. 重构更可靠
  4. 减少了代码层面的不必要的类型判断

Flow

安装和基本使用

  1. 安装flow,
npm init -y -> cnpm i flow-bin -D
  1. package.json中增加执行指令,
"flow": "flow"
  1. 初始化flow配置文件,
npm run flow init
  • `[ignore]: 忽略检测类型的文件
  • `[include]: 需要检测类型的文件
  1. 在项目中使用
  • 通过注释(不推荐)
// @flow 注释之后的内容才能被flow检测
/*: number */ 在需要检测的内容这样注释, 说明其中类型

  // @flow
  let a /*: number */ = 3;
  a = 'cc'
  console.log(a)
  • 直接改写js结构(需要babel, 类似ts语法了)
    • 安装bebel, cnpm i babel-cli、babel-preset-flow -D
    • 创建.babelrc文件,
  {
    "presets": [
      "flow"
    ]
  }
  • package.json文件中添加 "build": "babel ./src -d ./dist"

  • npm run build 通过babel把新增加的: number去除掉, 方便转码上线(与下面的指令区分开来)

  // @flow

  let a: number = 3;
  a = 'abc';
  console.log(a);
  • npm run flow 还是会检测数据类型
  • 执行npm run flow, 检测js内容

链接:www.jianshu.com/p/7716dc8b2… 来源:简书

原始类型

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

const a: string = 'foobar'
const b: number = Infinity // NaN // 100
const c: boolean = false // true
const d: null = null
const e: void = undefined
const f: symbol = Symbol()

数组类型

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

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

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

对象类型

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'

函数类型

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

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