【发布时间】:2019-08-14 16:41:41
【问题描述】:
我正在尝试使用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' 但类型 '{ type: "turnOff"; }'。 TS2345
如果我改为写turnOnAndOff(1000) as any,它可以正常工作。
如何让dispatch()接受函数?
【问题讨论】:
标签: typescript redux redux-thunk