flow JavaScript 静态类型检查工具

内置类型

flow 内置类型有 boolean, number, string, null, void, any, mixed, literal type.
其中 boolean, number, string 均为小写, 并与 JavaScript 内置的类型 Boolean, Number, String 不同.

JavaScript 中 null 的类型为 null, undefined 类型为 void.

any 是所有类型的父类或子类, mixed 是所有类型的父类.

可以用任意的 boolean, number, string 类型的字面量表示类型. 这对表示枚举或联合体非常有用.


type Suit =
  | "Diamonds"
  | "Clubs"
  | "Hearts"
  | "Spades";
type Rank =
  | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
  | "Jack"
  | "Queen"
  | "King"
  | "Ace";
type Card = {
  suit: Suit,
  rank: Rank,
}

数组和元组

数组

Array<T> 表示类型 T 的数组, 其简写为 T[].

元组

[<type1>, <type2>, <type3>, ...] 定义元组类型. 元组中的元素个数是类型的一部分, 因此不能用数组类型代替元组.

flow 支持 es6 中的类, 并部分支持原型类.

Class<T> 表示 T 类实例的类型.
T 表示实例的类型.

类是名义类型 (nominal typing, 类型判断根据名字), 对象和接口是结构类型 (struct typing, 类型判断根据内容).

this 可在类方法定义中作为输出值使用.

对象

对象类型通过对象字面量声明.

{ x1: T1; x2: T2; x3: T3;}

可选属性

var optObj: { a: string; b?: number } = { a: "hello" };

函数

协变

Maybe 类型

nullable

别名

Union 和 Intersection

Union 类型表示值可以是任意输入类型.
Intersection 类型表示值必须符合所有输入类型 (struct typing).

Union: <type 1> | <type 2> ... | <type n>
Intersection: <type 1> & <type 2> ... & <type n>

typeof

flow 中类型声明部分可以通过 typeof 来使用其他变量的类型.

声明

原文地址:https://www.cnblogs.com/wbin91/p/6370148.html