Skip to main content

类型注释

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

¥Adding type annotations is an important part of your interaction with Flow.

Flow 具有强大的推断程序类型的能力。大多数例如,你不必为 Array.map 这样的常见模式生成注释:

¥Flow has a powerful ability to infer the types of your programs. The majority For example, you don't have to produce annotations for common patterns like Array.map:

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

尽管如此,还是有一些地方你需要添加类型。

¥Still, there are places where you'll want to add types.

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

¥Imagine the following concat function for concatenating two strings together.

1function concat(a, b) {2  return a + b;3}

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

¥You need to add annotations on parameters of concat, so that Flow can type check its body. Now you'll get a warning from Flow if you are calling this function with unexpected types.

1function concat(a: string, b: string) {2  return a + b;3}4
5concat("A", "B"); // Works!6concat(1, 2); // Error!

本指南将教你 Flow 中所有不同类型的语法和语义。

¥This guide will teach you the syntax and semantics of all the different types you can have in Flow.