跳至主要内容

字面量类型

Flow 有 原始类型 用于字面量值,但也可以使用字面量值作为类型。

例如,我们可以接受字面量值 2,而不是接受 number 类型。

1function acceptsTwo(value: 2) { /* ... */ }2
3acceptsTwo(2);   // Works!4
5acceptsTwo(3);   // Error!
6acceptsTwo("2"); // Error!
5:12-5:12: Cannot call `acceptsTwo` with `3` bound to `value` because number [1] is incompatible with number literal `2` [2]. [incompatible-call]
6:12-6:14: Cannot call `acceptsTwo` with `"2"` bound to `value` because string [1] is incompatible with number literal `2` [2]. [incompatible-call]

您可以将原始值用于这些类型

  • 布尔值:如 truefalse
  • 数字:如 423.14
  • 字符串:如 "foo""bar"
  • 大整数:如 42n

将这些与 联合类型 一起使用非常强大

1function getColor(name: "success" | "warning" | "danger") {2  switch (name) {3    case "success" : return "green";4    case "warning" : return "yellow";5    case "danger"  : return "red";6  }7}8
9getColor("success"); // Works!10getColor("danger");  // Works!11
12getColor("error");   // Error!
12:10-12:16: Cannot call `getColor` with `"error"` bound to `name` because string [1] is incompatible with literal union [2]. [incompatible-call]

如果适合您的用例,请考虑使用 Flow 枚举 而不是字面量类型的联合。