Skip to main content

也许类型

你可以在类型前加上 ? 前缀,使其成为带有 nullvoid联合?T 相当于并集 T | null | void

¥You can prefix a type with ? to make it a union with null and void: ?T is equivalent to the union T | null | void.

例如,?number 相当于 number | null | void,并且允许使用数字、nullundefined 作为值。这是 "或许" 号码。

¥For example, ?number is equivalent to number | null | void, and allows for numbers, null, and undefined as values. It's "maybe" a number.

1function acceptsMaybeNumber(value: ?number) {2  // ...3}4
5acceptsMaybeNumber(42);        // Works!6acceptsMaybeNumber();          // Works! (implicitly undefined)7acceptsMaybeNumber(undefined); // Works!8acceptsMaybeNumber(null);      // Works!9acceptsMaybeNumber("42");      // Error!

对于对象来说,缺失的属性与显式的 undefined 属性不同。

¥In the case of objects, a missing property is not the same thing as an explicitly undefined property.

1function acceptsMaybeProp({value}: {value: ?number}) {2  // ...3}4
5acceptsMaybeProp({value: undefined}); // Works!6acceptsMaybeProp({});                 // Error!

如果要允许缺少属性,请使用 可选属性 语法,其中 ? 放置在冒号之前。还可以将两种语法组合起来用于可选的可能类型,例如 {value?: ?number}

¥If you want to allow missing properties, use optional property syntax, where the ? is placed before the colon. It is also possible to combine both syntaxes for an optional maybe type, for example {value?: ?number}.

精炼可能型

¥Refining maybe types

假设我们有类型 ?number,如果我们想将该值用作 number,我们需要首先检查它不是 nullundefined

¥Imagine we have the type ?number, if we want to use that value as a number we'll need to first check that it is not null or undefined.

1function acceptsMaybeNumber(value: ?number): number {2  if (value !== null && value !== undefined) {3    return value * 2;4  }5  return 0;6}

你可以使用单个 != null 检查来简化针对 nullundefined 的两项检查,该检查将同时执行这两项操作。

¥You can simplify the two checks against null and undefined using a single != null check which will do both.

1function acceptsMaybeNumber(value: ?number): number {2  if (value != null) {3    return value * 2;4  }5  return 0;6}

JavaScript 中不鼓励大多数双重相等检查,但上述模式是安全的(它精确检查 nullundefined)。

¥Most double equal checks are discouraged in JavaScript, but the above pattern is safe (it checks for exactly null and undefined).

你还可以翻转它,并在使用之前检查以确保该值的类型为 number

¥You could also flip it around, and check to make sure that the value has a type of number before using it.

1function acceptsMaybeNumber(value: ?number): number {2  if (typeof value === 'number') {3    return value * 2;4  }5  return 0;6}

但是,类型细化可能会丢失。例如,在细化对象属性的类型后调用函数将使该细化无效。请参阅 细化失效 文档了解更多详细信息,了解 Flow 为何以这种方式工作,以及如何避免这种常见陷阱。

¥However, type refinements can be lost. For instance, calling a function after refining the type of an object's property will invalidate this refinement. Consult the refinement invalidations docs for more details, to understand why Flow works this way, and how you can avoid this common pitfall.