リテラル型
Flow にはリテラル値用の プリミティブ型 がありますが、リテラル値を型として使用することもできます。
たとえば、number
型を受け入れる代わりに、リテラル値 2
だけを受け入れることができます。
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]
これらの型にはプリミティブ値を使用できます
- ブール:
true
やfalse
など - 数値:
42
や3.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 列挙型 を検討してください。