流动型标注函数返回类型
问题描述:
我需要在流动型注释其返回一个对象的函数,我看我有几种选择:流动型标注函数返回类型
A)诠释对象导出和功能
const getForecastHourly:ActionType = (query:number):ActionType => ...
B)注释仅在功能:
const getForecastHourly = (query:number):ActionType => ...
C)上对象注释仅导出:
const getForecastHourly:ActionType = (query:number) => ...
在我的代码中,我使用的是版本A),但是我想知道B或C是否可以等价,哪个版本是可以理解的以及为什么。
// @flow
import {ActionType} from '../../types'
import 'isomorphic-fetch'
import * as api from '../../app/api'
import * as types from './forecastHourlyActionTypes'
const getForecastHourly:ActionType = (query:number):ActionType => ({
type: types.GET_FORECAST_HOURLY,
payload: new Promise((resolve, reject) => {
fetch(api.forecast(query)).then(response => {
resolve(response.json())
})
})
})
const setForecastHourlyActiveReportType:ActionType = (type:string):ActionType => ({
type: types.SET_FORECAST_HOURLY_ACTIVE_REPORT_TYPE,
payload: type
})
export { getForecastHourly, setForecastHourlyActiveReportType }
export type ActionType ={
+type:string,
+payload: Object
}
答
我做的是仅标注功能本身就像
const getForecastHourly = (query: number): ActionType => ({ /* - */ });
因为flow
知道const
,它知道价值无法改变,并将自己的类型。
另一方面,如果您使用的是let
,那么我也会注释变量本身,因此flow
可以检查重新赋值,如果它具有正确的类型。