useReducer ActionsType无法使有效负载类型安全

时间:2019-03-22 10:57:08

标签: typescript react-hooks

我正在使用带有类型脚本的react hook useReducer,并且无法使其具有类型安全性,因为每当尝试为操作类型提供有效负载时,它都会返回错误。

interface State {
  checkedEvents: string[];
  seriesIndex: number;
  listHeight: number;
  chart: Chart | undefined;
}

interface ComponentActions {
  type: 'setInitialOptions' | 'setCheckedEvents';
  payload: State | { checkedEvents: string[] };
}

function reducer(state: State, action: ComponentActions): State {
  const { type, payload } = action;
  switch (type) {
    case 'setInitialOptions':
      return {
        chart: payload.chart,
        checkedEvents: payload.checkedEvents,
        seriesIndex: payload.seriesIndex,
        listHeight: payload.listHeight
      };
    case 'setCheckedEvents':
      return { ...state, checkedEvents: payload.checkedEvents };
    default:
      throw new Error();
}

这是类型错误的样子: enter image description here

为什么会发生这种情况以及如何使有效载荷类型安全?

1 个答案:

答案 0 :(得分:1)

声明所有动作的接口 并在减速器中使用

class Chart {
    some: string = "";
}

interface State {
    checkedEvents: string[];
    seriesIndex: number;
    listHeight: number;
    chart: Chart | undefined;
}

const SET_INITIAL_OPTIONS = "setInitialOptions";
type SET_INITIAL_OPTIONS = typeof SET_INITIAL_OPTIONS;
const SET_CHECKED_EVENTS = "setCheckedEvents";
type SET_CHECKED_EVENTS = typeof SET_CHECKED_EVENTS;

interface ISetInitialOptionsAction {
    type: SET_INITIAL_OPTIONS;
    payload: State;
}

interface ISetCheckedEventsAction {
    type: SET_CHECKED_EVENTS;
    payload: { checkedEvents: string[] };
}

type ComponentActions = ISetInitialOptionsAction | ISetCheckedEventsAction;

export default function reducer(state: State, action: ComponentActions): State {
    switch (action.type) {
        case SET_INITIAL_OPTIONS:
            return {
                chart: action.payload.chart,
                checkedEvents: action.payload.checkedEvents,
                seriesIndex: action.payload.seriesIndex,
                listHeight: action.payload.listHeight
            };
        case SET_CHECKED_EVENTS:
            return {
                 ...state, 
                 checkedEvents: action.payload.checkedEvents
            };
        default:
            throw new Error();
    }
}

package.json:

"typescript": "^3.3.1"

构建成功。 ¯\_(ツ)_/¯