跳至主要内容

宣布类型转换

从 0.3.0 版本开始,Flow 支持类型转换表达式。

类型转换表达式是一种对任何 JavaScript 表达式进行类型注释的简单方法。以下是一些类型转换的示例

(1 + 1 : number);
var a = { name: (null: ?string) };
([1, 'a', true]: Array<mixed>).map(fn);

对于任何 JavaScript 表达式 <expr> 和任何 Flow 类型 <type>,您可以编写

(<expr> : <type>)

注意: 括号是必需的。

类型转换的工作原理

要评估类型转换表达式,Flow 将首先检查 <expr> 是否为 <type>

(1+1: number); // this is fine
(1+1: string); // but this is is an error

其次,Flow 将推断类型转换表达式 (<expr>: <type>) 的类型为 <type>

[(0: ?number)]; // Flow will infer the type Array<?number>
[0]; // Without the typecast, Flow infers the type Array<number>

安全性

类型转换遵循与其他类型注释相同的规则,因此它们提供相同的安全保证。这意味着它们是安全的,除非您明确使用 any 类型来禁用 Flow 的类型检查。以下是一些向上转换(允许)、向下转换(禁止)和使用 any 的示例。

class Base {}
class Child extends Base {}
var child: Child = new Child();

// Upcast from Child to Base, a more general type: OK
var base: Base = new Child();

// Upcast from Child to Base, a more general type: OK
(child: Base);

// Downcast from Base to Child: unsafe, ERROR
(base: Child);

// Upcast base to any then downcast any to Child.
// Unsafe downcasting from any is allowed: OK
((base: any): Child);

更多示例

类型转换对于检查假设和帮助 Flow 推断您想要的类型特别有用。以下是一些示例

(x: number) // Make Flow check that x is a number
(0: ?number) // Tells Flow that this expression is actually nullable.
(null: ?number) // Tells Flow that this expression is a nullable number.

转换

与类型注释和其他 Flow 功能一样,类型转换需要在代码运行之前进行转换。转换将在 react-tools 0.13.0 发布后可用,但目前它们在 0.13.0-beta.2 中可用,您可以使用以下命令安装:

npm install react-tools@0.13.0-beta.2