我尝试通过在不使用额外的"compose"
utils(此处为简化版本: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
}
}
答案 0 :(得分:0)
通过更改两行来解决此问题:
type StateII = { otherVal: string } & StateI
然后合并状态
default:
return { ...state, ...reducerI(state, action) };
此处的示例:https://codesandbox.io/s/typescript-playground-export-d7u6w