typescript - 打字稿简单的减速器组成
问题描述
我尝试通过在不使用额外工具的情况下组合它们来扩展减速器功能"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
}
}
解决方案
通过更改两行来解决此问题:
type StateII = { otherVal: string } & StateI
只是合并状态
default:
return { ...state, ...reducerI(state, action) };
此处示例:https ://codesandbox.io/s/typescript-playground-export-d7u6w
推荐阅读
- python - 通过更新其他组件来更改 Dash 组件的可见性 - 默认为“隐藏”
- php - Laravel 8 使用 with() 从多个模型中检索数据,返回相关模型的空数组
- python - Coolprop 无法计算数值
- python - Pandas 将整数零和一转换为布尔值
- docker - 如何在 DockerImageStepTask 中从复制中排除文件?
- here-api - 这里 geocode api 给出了双重结果
- c# - Http 安全通道无法创建 SSL 和 TSL
- python - Python 线程:使用长时间运行的 C 扩展的 Python gevent
- install4j - 安装 GUI 和 CLI 模式时如何处理重启、关机
- java - Springboot 应用程序在 Tomcat 8.5 中工作,但在 Tomcat 9.0.3 中部署时不工作