Literal Types

Literal Types

Flow has primitive types for literal values, but can also use literal values as types.

For example, instead of accepting number type, we could accept only the literal value 2.

// @flow
function acceptsTwo(value: 2) {
  // ...
}

acceptsTwo(2);   // Works!
// $ExpectError
acceptsTwo(3);   // Error!
// $ExpectError
acceptsTwo("2"); // Error!

You can use primitive values for these types:

  • Booleans: like true or false
  • Numbers: like 42 or 3.14
  • Strings: like "foo" or "bar"

Using these with union types is powerful:

// @flow
function getColor(name: "success" | "warning" | "danger") {
  switch (name) {
    case "success" : return "green";
    case "warning" : return "yellow";
    case "danger"  : return "red";
  }
}

getColor("success"); // Works!
getColor("danger");  // Works!
// $ExpectError
getColor("error");   // Error!

© 2013–present Facebook Inc.
Licensed under the BSD License.
https://flow.org/en/docs/types/literals

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部