【问题标题】:How can i have a interface check in typescript switch statements?如何在 typescript switch 语句中进行接口检查?
【发布时间】:2021-04-08 13:05:40
【问题描述】:

我正在使用 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;
  }
}

【问题讨论】:

    标签: node.js typescript redux interface switch-statement


    【解决方案1】:

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

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

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

    【讨论】:

    • 我比较了使用switch(action.type) 然后这样做是为了让打字稿开心(action as IncrementAction).incBy
    • 没错,你基本上在之后使用as 操作符进行转换。这是因为您正在使用他的开关对运行时进行检查。在运行时执行操作时,您希望使用类型保护。只是不要重复自己查看 redux 工具包或 redux 操作。 redux-toolkit.js.org/api/createSlice我不会使用原始减速器和你那里拥有的工具数量
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多