简体   繁体   中英

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

I am using Typescript and redux

I want to compare passed action with an interface and then perform the task

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;
  }
}

Maybe you can check into type guards for that.

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

I would probably use redux-toolkit or redux-actions for that because it simplifies a lot your code and it has Typescript support

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM