Flow用起來是的確是簡單,但里面的內容很多,主要原因是是要看實際不同的使用情況作搭配。JavaScript里面的原始數據類型都有支持,而在函數、對象與一些新的ES6中的類,在搭配使用時就會比較復雜,詳細的情況就請到官網文檔查看,以下只能提供一些簡單的介紹說明。
Flow所定義的基本類型與 js 的基本數據類型類似,包括:
* `boolean`: 對應 js 的 Boolean 類型
* `number`: 對應 js 的 Number 類型
* `string`: 對應 js 的 String 類型
* `null`: 對應 js 的 null
* `void`: 對應 js 的 undefined
接下來,我們一個一個來看。
</br>
## Boolean類型
```
// @flow
function acceptsBoolean(value: boolean) {
// ...
}
acceptsBoolean(true); // 成功!
acceptsBoolean(false); // 成功!
acceptsBoolean("foo"); // 報錯!
acceptsBoolean(Boolean("foo")); // 報錯!
acceptsBoolean(!!("foo")); // 報錯!
```
從上面還可以看出,在Flow中,默認并不會轉換類型。如果你需要轉換類型請使用顯示或隱式轉換。
</br>
## Number類型
```
// @flow
function acceptsNumber(value: number) {
// ...
}
acceptsNumber(42); // 成功!
acceptsNumber(3.14); // 成功!
acceptsNumber(NaN); // 成功!
acceptsNumber(Infinity); // 成功!
acceptsNumber("foo"); // 報錯!
```
</br>
## String類型
```
// @flow
function acceptsString(value: string) {
// ...
}
acceptsString("foo"); // 成功!
acceptsString("3.14"); // 成功!
acceptsString(3.14); // 報錯!
acceptsString([]); // 報錯!
```
</br>
## Null類型和Void類型
```
// @flow
function acceptsNull(value: null) {
/* ... */
}
function acceptsUndefined(value: void) {
/* ... */
}
acceptsNull(null); // 成功!
acceptsNull(undefined); // 報錯!
acceptsUndefined(null); // 報錯!
acceptsUndefined(undefined); // 成功!
```