Literal Types

Using literal values as 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.

1
2
3
4
5
6
7
8
9
10
// @flow
function acceptsTwo(value: 2) {
  // ...
}

acceptsTwo(2);   // Works!
// $ExpectError
acceptsTwo(3);   // Error!
// $ExpectError
acceptsTwo("2"); // Error!
number Expected number literal `2`, got `3` instead number literal `2` string This type is incompatible with the expected param type of number literal `2`

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
// @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!
string This type is incompatible with the expected param type of string enum