我正在尝试使用redux-thunk创建异步操作。几乎可以使用,但是唯一的问题是dispatch(f())
会导致TSC错误。
阅读redux official document时,它接受功能。
代码在这里:
import { applyMiddleware, createStore, Reducer } from 'redux';
import thunkMiddleware, { ThunkAction } from 'redux-thunk';
// --------------------------------
// State
export interface IAppState {
active: boolean;
}
const initialAppState: IAppState = {
active: false,
};
// --------------------------------
// Actions and action creators
type AppAction = { type: 'turnOn' } | { type: 'turnOff' };
function turnOn (): AppAction {
return { type: 'turnOn' };
}
function turnOff (): AppAction {
return { type: 'turnOff' };
}
// --------------------------------
// Reducers
const rootReducer: Reducer<IAppState, AppAction> = (
state = initialAppState,
action,
) => {
switch (action.type) {
case 'turnOn': return { ...state, active: true };
case 'turnOff': return { ...state, active: false };
default: return state;
}
};
// --------------------------------
// Store
export function createAppStore () {
return createStore<IAppState, AppAction, {}, {}>(
rootReducer,
applyMiddleware(thunkMiddleware),
);
}
const store = createAppStore();
// --------------------------------
// Use store
store.dispatch(turnOn());
store.dispatch(turnOff());
// --------------------------------
// Thunk action
function turnOnAndOff (
delay: number,
): ThunkAction<Promise<void>, IAppState, null, AppAction> {
return (dispatch) => new Promise((resolve) => {
dispatch(turnOn());
setTimeout(() => {
dispatch(turnOff());
resolve();
}, delay);
});
}
store.dispatch(turnOnAndOff(1000)); // ERROR
在最后一行,TSC说它们的类型不匹配。
TypeScript错误:无法将类型'ThunkAction
,IAppState,null,AppAction>'的参数赋给'AppAction'类型的参数。
类型'ThunkAction,IAppState,null,AppAction>'中缺少属性'type',但类型'{类型:“ turnOff”;中必需}'。 TS2345
如果我改写了turnOnAndOff(1000) as any
,它就可以正常工作。
如何让dispatch()
接受该功能?
答案 0 :(得分:1)
当前的redux-thunk类型不支持使用store.dispatch来调度thunk动作。通常,您会有一个mapDispatchToProps,您可以在其中键入调度为ThunkDispatch。您可以进行内联强制转换,即使它很丑并且强制转换失去类型安全性。查看此答案:How to dispatch an Action or a ThunkAction (in TypeScript, with redux-thunk)?