我如何在 typescript switch 语句中进行接口检查?

How can i have a interface check in typescript switch statements?

我正在使用 Typescript 和 redux

我想将传递的操作与接口进行比较,然后执行任务

export function counterReducer(
  state = initialState,
  action: CounterActionTypes
): CounterState {
  switch (action) {
    case IncrementAction:
      return { ...state, count: state.count + action.incBy };
    case action as DecerementAction:
      return { ...state, count: state.count + action.decBy };
    default:
      return state;
  }
}

也许你可以检查一下类型保护。

https://www.typescriptlang.org/docs/handbook/advanced-types.html

我可能会为此使用 redux-toolkitredux-actions,因为它大大简化了您的代码并且支持 Typescript