使用flowtype的最佳实践redux操作?

时间:2017-04-11 06:26:38

标签: redux flowtype

我想用flowtype编写redux,但我对如何做到这一点有疑问。

Redux with Flowtype

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声明我们在我们的应用中使用的所有操作的具体类型。

问题1:如何确保传递给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
  ;

有意义吗?

问题2:如何使用flowtype和Immutable.js编写reducers(和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检查payloadreducers类型的操作类型SELECT_COUNTRY

如何使用flowtype check将有效负载值应用于immutable状态?

1 个答案:

答案 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函数。