跳至主要内容

类型注解

添加类型注解是您与 Flow 交互的重要部分。

Flow 具有强大的推断程序类型的能力。大多数情况下,例如,您不需要为像 Array.map 这样的常见模式生成注解。

1["foo", "bar"].map(s => ( // s is inferred to have type string2  s.length3));

尽管如此,您仍然需要在某些地方添加类型。

想象一下以下用于连接两个字符串的 concat 函数。

1function concat(a, b) {
2 return a + b;3}
1:17-1:17: Missing an annotation on `a`. [missing-local-annot]
1:20-1:20: Missing an annotation on `b`. [missing-local-annot]

您需要在 concat 的参数上添加注解,以便 Flow 可以对它的主体进行类型检查。现在,如果您使用意外类型调用此函数,您将收到 Flow 的警告。

1function concat(a: string, b: string) {2  return a + b;3}4
5concat("A", "B"); // Works!6concat(1, 2); // Error!
6:8-6:8: Cannot call `concat` with `1` bound to `a` because number [1] is incompatible with string [2]. [incompatible-call]
6:11-6:11: Cannot call `concat` with `2` bound to `b` because number [1] is incompatible with string [2]. [incompatible-call]

本指南将向您介绍 Flow 中所有不同类型的语法和语义。