Flow 简介

开始使用 flow

  1. 安装 flow 环境

    yarn add -D flow-bin
    yarn flow init
    yarn flow start
    
  2. 代码块

    // @flow
    
    function sum(a: number, b: number) {
     return a + b;
    }
    
    sum('1', '2');
    
  3. 删除类型注解才能运行

  4. 方法一

    # 安装删除注解模块到本地
    yarn add --dev flow-remove-types
    # 执行删除注解命令
    yarn flow-remove-types ./ -d dist
    
  5. 方法二

    yarn add @babel/cli @babel/core @babel/preset-flow
    

    添加 .babelrc 文件到项目根目录

    {
      "presets": ["@babel/preset-flow"]
    }
    

    执行 babel 转码命令

    yarn babel src -d dist
    

Flow 开发工具插件

flow language surpport

Flow 类型推断

// @flow

function square(n: number) {
  return Math.pow(n, 2);
}

// square('100');
square(100);

Flow 类型注解

// @flow

function square(n: number): number {
  return Math.pow(n, 2);
}

let num: number = 100;

function foo(): number {
  return 2;
}

function bar(): void {}

原始类型

// @flow
const a: string = 'foobar';
const b: number = Infinity; // 100 NaN
const c: boolean = false; // true
const d: null = null;
const e: void = undefined; // 特殊的约定
const f: symbol = Symbol();

数组类型

// @flow

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

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

对象类型

// @flow

const obj1: { foo: string, bar: number } = { foo: 'foo', bar: 1 };
const obj2: { foo?: string, bar: number } = { bar: 2 };
const obj3: { [string]: string } = {};

obj3.k1 = 'v1';
obj3.k2 = 'v2';

函数类型

// @flow

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

foo(function( str, n)) {}

其他类型

// @flow

const a: 'foo' = 'foo'; // 字面量类型

// 配合联合类型使用
const type: 'success' | 'warning' | 'danger' = 'success';

const b: string | number = '100';

// 使用 type 关键字声明类型

type StringOrNumber = string | number;

const c: StringOrNumber = 'string or number';

const gender: ?number = null; // maybe
const vender: ?number = undefined; // maybe

类型说明文档查询

flow
salty

运行环境参考

a
b
c
d
e

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值