• 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
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 相关阅读:
    回文链表
    istringstream
    编写函数,以读模式打开一个文件,将其内容读入到一个string的vector中,将每一行作为一个对立的元素存于vector中
    c++ primer,友元函数上的一个例子(By Sybase)
    类的静态成员
    聚合类和字面值常量类
    隐式的类类型转换
    构造函数
    类的作用域
    类的其他特性
  • 原文地址:https://www.cnblogs.com/sexintercourse/p/11963927.html
Copyright © 2020-2023  润新知