zoukankan      html  css  js  c++  java
  • Flow入门初识

    Flow是facebook出品的JavaScript静态类型检查工具。
    由于JavaScript是动态类型语言,它的灵活性也会造成一些代码隐患,使用Flow可以在编译期尽早发现由类型错误引起的bug,这种方式非常有利于大型项目源码的开发和维护,

    1.Flow工作方式

    类型推断:通过变量的使用上下文来推断,然后根据这些推断来判断类型。
    类型注释:事先注释数据类型,Flow会基于注释来判断。

    2.Flow安装

    $mkdir flowtest
    $npm install --g flow-bin
    
    $flow init  //初始化,创建一个.flowconfig文档
    $flow

    3.使用

    // @flow
    function square(n: number): number {
        return n * n;
      }
      
      square("2"); // Error!
    
    $flow
     
     

    (1)原始数据类型

    // @flow
    function concat(a: string, b: string) {
        return a + b;
      }
      concat("1", 2); // Error!
    
    // @flow
    function method(x: number, y: string, z: boolean) {
      // ...
    }
    
    method(3.14, "hello", true);//No errors!
    
    // @flow
    function method(x: Number, y: String, z: Boolean) {
      // ...
    }
    
    method(new Number("111"), new String("world"), new Boolean(false));//No errors!
    

    (2)类和对象
    Object

    // @flow
    var obj1: { foo: boolean } = { foo: true };
    var obj2: {
      foo: number,
      bar: boolean,
      baz: string,
    } = {
      foo: 1,
      bar: true,
      baz: 'three',
    };//No errors!
    
    //@flow
    class Bar {
        x: string;           // x 是字符串
        y: string | number;  // y 可以是字符串或者数字
        z: boolean;
      
        constructor(x: string, y: string | number) {
          this.x = x
          this.y = y
          this.z = false
        }
      }
    var bar: Bar = new Bar('hello', 4)
    
    var obj: { a: string, b: number, c: Array<string>, d: Bar } = {
      a: 'hello',
      b: 11,
      c: ['hello', 'world'],
      d: new Bar('hello', 3)
    }
    //No errors!
    

    Array

    //@flow
    let arr: Array<number> = [1, 2, 3];
    

    (3)自定义类型
    Flow 提出了一个 libdef 的概念,可以用来识别这些第三方库或者是自定义类型。例如vuejs的对flow的使用。vue源码下flow文件夹。



    作者:藕藕藕汀
    链接:https://www.jianshu.com/p/197d8912b50d
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 相关阅读:
    python 发送邮件 email
    python 日志 logging
    python 判断当前环境是什么系统 platform 模块
    pandas to_excel 添加颜色
    Pandas excel 双标题 多级索引 层次化索引 MultiIndex
    windows10 安装 pyltp python3.6
    Python的内存管理
    pandas 中 DataFramt 改变 列的顺序
    元组
    基本语法
  • 原文地址:https://www.cnblogs.com/sexintercourse/p/11963927.html
Copyright © 2011-2022 走看看