我是 typescript 的新手,但意识到我知道如何解决这个问题。
在reducer中我们通常导入action类型,它是这样的:
// actions.ts
import { action } from 'typesafe-actions';
import actionTypes from './actionTypes';
export const someAction = (data) = action(
actionTypes.SOME_ACTION_TYPE,
{ data },
);
// reducer.ts
import { ActionType } from 'typesafe-actions';
import { StateSlice } from './types';
import * as actions from './actions';
const initialState: StateSlice = { ... };
const reducer = (state = initialState, action: ActionType<typeof actions>): StateSlice => {
...
};
因此,要更新它以接受已被 redux-logic 中间件修改的操作,我们必须告诉 typescript 该类型已被扩展。它是这样的:
// actions.ts
import { action } from 'typesafe-actions';
import actionTypes from './actionTypes';
export const someAction = (data) = action(
actionTypes.SOME_ACTION_TYPE,
{ data },
);
// reducer.ts
import { ActionType } from 'typesafe-actions';
import { StateSlice, SOME_TYPE } from './types';
import * as actions from './actions';
type OriginalAction = ActionType<typeof actions.someAction>;
interface MutatedAction1 extends OriginalAction {
payload: OriginalAction['payload'] & {
thingWeAddedInReduxLogic: SOME_TYPE;
};
}
// repeat for other actions, then use a union type like this
type MutatedActionType = MutatedAction1 | MutatedAction2 | ... ;
const initialState: StateSlice = { ... };
const reducer = (state = initialState, action: MutatedActionType): StateSlice => {
...
};
这是我能够制作的真实代码的缩写版本。希望这对某人有所帮助。