タイプの注釈付け
タイプの注釈を追加することは、Flowとのインタラクションの重要な部分です。
Flowには、プログラムの型を推測する強力な能力があります。たとえば、Array.map
のような一般的なパターンについては注釈を作成する必要はありません。
1["foo", "bar"].map(s => ( // s is inferred to have type string2 s.length3));
それでも、型を追加したい場所があります。
2つの文字列を連結するための次のconcat
関数を考えてみます。
1function concat(a, b) { 2 return a + b;3}
1:17-1:17: Missing an annotation on `a`. [missing-local-annot]1:20-1:20: Missing an annotation on `b`. [missing-local-annot]
concat
のパラメータに注釈を追加して、Flowがその本体の型チェックを実行できるようにする必要があります。予想外の型でこの関数を呼び出した場合、Flowから警告が表示されます。
1function concat(a: string, b: string) {2 return a + b;3}4
5concat("A", "B"); // Works!6concat(1, 2); // Error!
6:8-6:8: Cannot call `concat` with `1` bound to `a` because number [1] is incompatible with string [2]. [incompatible-call]6:11-6:11: Cannot call `concat` with `2` bound to `b` because number [1] is incompatible with string [2]. [incompatible-call]
このガイドでは、Flowで持つことができるさまざまな型すべての構文と意味を紹介します。