我想用flowtype编写redux,但我对如何做到这一点有疑问。
type ActionType =
| 'A'
| 'B'
;
// A generic type conforming to Flux Standard Action
type ActionT<A, P> = {|
type: A,
payload?: P | Error,
error?: boolean,
meta?: mixed
|};
type Action =
| ActionT<'A', string>
| ActionT<'B', number>
;
const error: Error = new Error('wrong');
const info = { href: '...' };
// ---- valid actions with flowtype ----
const action1: Action = {type: 'A', payload: 'hello' };
const action2: Action = {type: 'A', payload: error, error: true }; // The 'payload' could be an error.
const action3: Action = {type: 'A', payload: 'hello', meta: info }; // We can have 'meta'.
// ---- invalid actions with flowtype ----
const actionNG1: Action = {type: 'C', payload: 'hello' }; // Wrong 'type' value. The type 'C' is not allowed.
const actionNG2: Action = {type: 'B', payload: 'hello' }; // Wrong value type of 'payload'. It should be a number.
const actionNG3: Action = {type: 'A', payload: 'hello', threshold: 3 }; // Extra property 'threshold' is not allowed. It should conform to type ActionT.
ActionType
而不是常量来检查有效的type
值。 ActionT
符合Flux Standard Action以确保Redux操作的结构。Action
声明我们在我们的应用中使用的所有操作的具体类型。ActionT
的第一个类型是ActionType
的类型(或者至少应该是string
类型)?例如,在不允许的情况下添加新类型'C'
,因为ActionType
仅接受'A'
和'B'
。
type ActionType =
| 'A'
| 'B'
;
type Action =
| ActionT<'A', string>
| ActionT<'B', number>
| ActionT<'C', number> // Should Raise an error
;
有意义吗?
thunk
)?我已经编写了一个buildReducer来绑定初始状态。
type Action =
| ActionT<'SELECT_COUNTRY', string>
;
const buildReducer = (initialState, reducerMap) =>
(state = initialState, action) => {
const reducer = reducerMap[action.type];
return (reducer) ? reducer(state, action) : state;
};
const initialState = Immutable.fromJS({
selectedCountry: 'US'
})
const reducers = {
['SELECT_COUNTRY']: (state, action) => {
// how to know the type of payload is string type?
// how to ensure that `state.set(...)` gets right type of the value for the key?
return state.set('selectedCountry', action.payload)
}
}
const appReducer = buildReducer(initialState, reducers)
如何使用flowtype检查payload
中reducers
类型的操作类型SELECT_COUNTRY
?
如何使用flowtype check将有效负载值应用于immutable
状态?
答案 0 :(得分:3)
要回答问题1,您可以使用有界多态性
// A generic type conforming to Flux Standard Action
type ActionT<A: ActionType, P> = {|
type: A,
payload?: P | Error,
error?: boolean,
meta?: mixed
|};
注意我们如何将通用参数A
绑定到ActionType
要回答问题2,你必须确保在这里输入immutable-js类型:https://github.com/facebook/immutable-js/blob/master/type-definitions/immutable.js.flow然后输入你的reducer函数。