如何添加默认的通用类型-使用Flow键入createReducer

时间:2018-12-06 11:53:47

标签: javascript flowtype

Here,您会看到方便的createReducer() 您将如何使用Flow键入它?

这是我的例子

// @flow
import type { TAction as TActionDefault } from '../actions/types';

type THandlers<TState, TAction> = {
  [key: string]: (state: TState, action: TAction) => any
}

type TReducer<TState, TAction> = (state: TState, action: TAction) => TState


export default function createReducer<TState, TAction>(
  initialState: TState,
  handlers: THandlers<TState, TAction>
): TReducer<TState, TAction> {
  return function reducer(state: TState = initialState, action: TAction): TState {
    if (handlers[action.type]) {
      return handlers[action.type](state, action)
    } else {
      return state
    }
  }
}

但是这里有个问题

Cannot get `action.type` because property `type` is missing in `TAction` [1]. (References: [1])

流程不允许我将默认类型值赋予TAction

那么在这种情况下和类似情况下您会怎么做?

1 个答案:

答案 0 :(得分:0)

问题出在这里

createReducer<TState, TAction>

我试图像这样向通用名称添加默认值

createReducer<TState, TAction = TActionDefault>

这是正确的方法。

createReducer<TState, TAction: TActionDefault>

所以最终代码看起来像这样

// @flow
import type { TAction as TActionDefault } from '../actions/types';

type THandlers<TState, TAction> = {
  [key: string]: (state: TState, action: TAction) => TState
}

type TReducer<TState, TAction = any> = (state: TState, action: TAction) => TState


export default function createReducer<TState, TAction: TActionDefault<any>>(
  initialState: TState,
  handlers: THandlers<TState, TAction>
): TReducer<TState, TAction> {
  return function reducer(state: TState = initialState, action: TAction): TState {
    if (handlers[action.type]) {
      return handlers[action.type](state, action);
    }
    return state;
  };
}