*
:const foo: () => Array<*> = () => [777];
// Flow error:
// 13: const foo: () => Array<*> = () => [777];
// ^ number. This type is incompatible with
// 15: (foo(): Array<string>);
// ^ string
(foo(): Array<string>);
// No flow errors.
(foo(): Array<number>);
any
:const bar: () => Array<any> = () => [777];
// No flow errors.
(bar(): Array<string>);
// No flow errors.
(bar(): Array<number>);
用了any
基本上跟不檢查沒兩樣,甚至有可能污染到其他值。所以能不用就盡量不用。
關於any
mixed
:// Flow error:
// 1: const add5: (mixed) => number = a => a + 5;
// ^ mixed. This type cannot be used in an addition because it is unknown whether it behaves like a string or a number.
const add5: mixed => number = value => value + 5;
此錯誤訊息產生的原因官方文件記載如下:
When you try to use a value of a mixed type you must first figure out what the actual type is.
所以我們在進行+
運算前,必須先確認value
為number
或是string
。
官方文件範例是在運算前使用typeof value
來確認型別。
*
:// No flow errors.
const add5: * => number = value => value + 5;
// No flow errors.
(add5(2): number);
// Flow error:
// 1: const add5: (*) => number = a => a + 5;
// ^ string. This type is incompatible with
// 1: const add5: (*) => number = a => a + 5;
// ^ number
(add5('3'): number);
暫時還沒想到什麼情況是用*
會比較好,之後再補上。