Skip to main content

空类型

empty 类型没有值。它是 所有其他类型的子类型(即 底型)。这样它就与 mixed 相反,mixed 是所有类型的超类型。

¥The empty type has no values. It is the subtype of all other types (i.e. the bottom type). In this way it is the opposite of mixed, which is the supertype of all types.

使用 empty 注释代码并不常见。但是,在以下几种情况下它可能有用:

¥It is not common to annotate your code using empty. However, there are a couple of situations that it might be useful:

如果你有一个总是抛出异常的函数,你可以将返回注释为 empty,因为该函数永远不会返回:

¥If you have a function that always throws, you can annotate the return as empty, as the function never returns:

1function throwIt(msg: string): empty {2  throw new Error(msg);3}

你可以使用强制转换为 empty 来断言你已精炼掉联合的所有成员:

¥You can use a cast to empty to assert that you have refined away all members of a union:

1function f(x: 'a' | 'b'): number {2  switch (x) {3    case 'a':4      return 1;5    case 'b':6      return 2;7    default:8      return (x: empty);9  }10}

如果你没有检查联合体的所有成员(例如,将 x 更改为 'a' | 'b' | 'c' 类型),那么 x 将不再是 default 中的 empty,并且 Flow 将出错。

¥If you had not checked for all members of the union (for example, changed x to be of type 'a' | 'b' | 'c'), then x would no longer be empty in the default, and Flow would error.

注意:如果你希望默认情况下彻底检查枚举,而不必强制转换为 empty,则可以在项目中启用并使用 Flow 枚举

¥Note: If you want exhaustively checked enums by defualt, without having to cast to empty, you could enable and use Flow Enums in your project.

由于 empty 是所有类型的子类型,因此允许对具有 empty 类型的对象执行所有操作。然而,由于没有任何值可以是 empty,因此这是 "安全的",与 any 不同。

¥Since empty is the subtype of all types, all operations are permitted on something that has the empty type. However since no values can be empty, this is "safe", unlike with any.

1const str = "hello";2
3if (typeof str === "string") {4  (str: string); // Yes it's a string5} else {6  // Works! Since we will never enter this branch7  (str: empty);8  const n: number = str + 1;9}

我们将 "安全的" 放在上面的引号中,由于代码中的类型安全漏洞或 Flow 本身的错误,有可能获取 empty 类型的值。

¥We put "safe" in quotes above, as due type safety holes in your code or bugs within Flow itself, it is possible to get values which are empty typed.

你可以使用 覆盖范围 命令来识别键入为 empty 的代码。

¥You can use the coverage command to identify code typed as empty.