温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - Redux Thunk with Typescript
javascript reactjs typescript redux

javascript - Redux Thunk与打字稿

发布于 2020-03-27 11:13:15

我正在学习打字稿,并且想实现一个简单的React / Redux应用程序。当我使用同步操作时,它可以正常工作,但是异步操作存在问题。我正在关注官方的redux教程。

首先,我声明会话的状态

export interface UserSessionState {
  loggedIn: boolean;
}

然后我声明动作的接口

interface UpdateSessionAction {
  type: 'USER_LOGIN';
  payload: boolean;
}

我用联合类型导出它们

export type UserActionTypes = UpdateSessionAction;

然后我有实际的行动


export function updateSession(loggedIn: UserSessionState) {
  return {
    type: 'USER_LOGIN',
    payload: loggedIn,
  };
}

我有一个假的api呼叫

function api() {
  return Promise.resolve(true);
}

最后登录

export const userLogin = (): ThunkAction<
  void,
  {},
  {},
  AnyAction
> => async (dispatch: ThunkDispatch<{}, {}, AnyAction>) => {
  const res = await api();
  dispatch(updateSession({ loggedIn: res }));
};

在reducer中,我只是初始化状态

initialState: UserSessionState = {loggedIn: false}

然后,我为减速器执行常规的redux任务。

最后,在我的商店中,我调用初始操作以检查状态

store.dispatch(userLogin());

我不断收到此错误:

Argument of type 'ThunkAction<Promise<void>, {}, {}, AnyAction>' is not assignable to parameter of type 'AnyAction'.
  Property 'type' is missing in type 'ThunkAction<Promise<void>, {}, {}, AnyAction>' but required in type 'AnyAction'.

我想念一个,type但我不知道我做错了什么。

查看更多

查看更多

提问者
Kaiser Soze
被浏览
291
yuval.bl 2019-07-04 00:03

简而言之:

之所以出现此错误,是因为userLogin()函数返回的ThunkAction,而该缺失type

为什么会这样呢?

dispatch应该接受type的参数AnyActionAnyAction是redux类型,它进行扩展Action(具有必填属性 type)。

这来自当前的redux types文件

export interface Action<T = any> {
  type: T
}

/**
 * An Action type which accepts any other properties.
 * This is mainly for the use of the `Reducer` type.
 * This is not part of `Action` itself to prevent users who are extending `Action.
 */
export interface AnyAction extends Action {
  // Allows any extra properties to be defined in an action.
  [extraProps: string]: any
}

如何解决? 使用ThunkDispatchtype代替redux的standard Dispatch以下示例以及更多内容可以在此要旨中找到

const mapDispatchToProps = (dispatch: ThunkDispatch<MyState, void, Action>) => {
  return {
    onRequestClick: (arg: any) => dispatch(myAsyncAction(arg)),
  };
}

另外,看到这个文章,部分 map调度道具