首页 > 解决方案 > 打字稿简单的减速器组成

问题描述

我尝试通过在不使用额外工具的情况下组合它们来扩展减速器功能"compose"(此处的简化版本:https ://codesandbox.io/s/cd721 )

有没有办法执行这种模式,或者我应该尝试不同的方法?

enum ACTIONS_I {
  CHANGE_VAL = 'CHANGE_VAL'
}

type ActionI = {type: ACTIONS_I.CHANGE_VAL, val: number}

type StateI = {
  val: number;
}

const initStateI = {val: 0}

function reducerI(state: StateI = initStateI, action: ActionI): StateI {
  switch (action.type) {
    case ACTIONS_I.CHANGE_VAL:
      return { ...state, val: action.val };
    default:
      throw new Error();
  }
}

///////////////////////////////////

enum ACTIONS_II {
  CHANGE_OTHER_VAL = 'CHANGE_OTHER_VAL'
}

type ActionII = { type: ACTIONS_II.CHANGE_OTHER_VAL, otherVal: string } | ActionI

type StateII = { otherVal: string } | StateI 

const initStateII = { ...initStateI, otherVal: '' }

function reducerII(state: StateII = initStateII, action: ActionII): StateII {
  switch (action.type) {
    case ACTIONS_II.CHANGE_OTHER_VAL:
      return { ...state, otherVal: action.otherVal };
    default:
      return reducerI(state, action);
      // ^ ERROR HERE
  }
}

标签: typescript

解决方案


通过更改两行来解决此问题:

type StateII = { otherVal: string } & StateI

只是合并状态

default:
      return { ...state, ...reducerI(state, action) };

此处示例:https ://codesandbox.io/s/typescript-playground-export-d7u6w


推荐阅读