这里使用了 typesafe-actions
和 immer
两个开源库,下面函数简单模拟了一下 produce
函数结构:
// src/lib/immer.js
// 模拟 produce 结构,测试 ts 定义
interface IProduce {
<State, Action>(
handler: (state: State, action: Action) => State
): (state: State, action: Action) => State;
}
export const produce: IProduce = function(handler) {
return (state, action) => {
return handler(state, action);
};
};
import { createAction, createReducer } from 'typesafe-actions';
import { produce } from 'src/lib/immer';
const getLoginInfoSuccess = createAction(actionTypes.GET_LOGIN_INFO)<{
userInfo: {};
menuInfo: {};
}>();
const _initialState = {
userInfo: {},
menuInfo: {},
};
createReducer(_initialState)
/**
* @param {PayloadActionCreator} actionType
* @param {(state: TState, action: PayloadAction): TState} reducer
*/
.handleAction(
getLoginInfoSuccess,
(state, action) => {
// 可以看到 action 的定义
return state;
}
);
.handleAction(
getLoginInfoSuccess,
produce((state, action) => {
// action 显示 unknown
return state;
})
)
这样定义 produce
后,state
可以推断成功,但 action
始终不可以。