バージョン 0.3.0 以降のフローは、型キャスト表現をサポートしています。
型キャスト表現は、JavaScript の任意の表現に型注釈を追加する簡単な方法です。型キャストの例を次に示します。
(1 + 1 : number);
var a = { name: (null: ?string) };
([1, 'a', true]: Array<mixed>).map(fn);
JavaScript 表現 <expr>
とフロー型 <type>
を使用して、次のことができます。
(<expr> : <type>)
注: かっこは必須です。
型キャストの仕組み
フローは型キャスト表現を評価するために、最初に <expr>
が <type>
であるかどうかを確認します。
(1+1: number); // this is fine
(1+1: string); // but this is is an error
次に、フローは型キャスト表現 (<expr>: <type>)
は <type>
の型を持つと推測します。
[(0: ?number)]; // Flow will infer the type Array<?number>
[0]; // Without the typecast, Flow infers the type Array<number>
安全性
型キャストは他の型注釈と同じルールに従うため、同じ安全保証が提供されます。つまり、フローの型チェックを無効にするために any
型を明示的に使用しない限り、型キャストは安全です。アップキャスト(許可されています)、ダウンキャスト(禁止されています)、any
の使用の例を以下に示します。
class Base {}
class Child extends Base {}
var child: Child = new Child();
// Upcast from Child to Base, a more general type: OK
var base: Base = new Child();
// Upcast from Child to Base, a more general type: OK
(child: Base);
// Downcast from Base to Child: unsafe, ERROR
(base: Child);
// Upcast base to any then downcast any to Child.
// Unsafe downcasting from any is allowed: OK
((base: any): Child);
詳細
型キャストは、仮定を確認し、フローが目的の型を推測するのに役立てるために特に便利です。例を次に示します。
(x: number) // Make Flow check that x is a number
(0: ?number) // Tells Flow that this expression is actually nullable.
(null: ?number) // Tells Flow that this expression is a nullable number.
変換
型注釈や他のフロー機能と同様に、型キャストはコードを実行する前に変換する必要があります。変換は近日中に公開される react-tools 0.13.0
で利用できるようになりますが、現在は 0.13.0-beta.2
で利用できます。これは次のコマンドでインストールできます。
npm install react-tools@0.13.0-beta.2