Dispatch 没有使用带有打字稿的 redux-thunk 返回承诺

时间:2021-03-05 03:27:49

标签: typescript redux redux-thunk

我实际上正在将一些代码迁移到打字稿,所以我对所有这些类型的东西都是新手。当我将 redux-thunk 与常规 javascript 一起使用时,dispatch 方法返回了一个帮助我处理错误和内容的承诺。动作是这样的:

export const login = ({email, password}) => {
    return async function (dispatch) {
        try {
            const result = await api.post(`/auth/login`, {username, password});
            return dispatch({type: 'set_user_session', payload: result.data});
        } catch (err) {
            throw (err.response && err.response.data) || {code: err};
        }
    };
};

然后我使用 useDispatch 钩子正常调用:

const dispatch = useDispatch();
...
dispatch(login({username: "admin", password: "adminpassword1"}))
    .then(d => console.log("ok"))
    .catch(err => console.log(err));

现在我将代码迁移到 typescript,操作现在看起来像这样:

export const login = ({username, password}: Credentials): ThunkAction<Promise<Action>, {}, {}, AnyAction> => {
    // Invoke API
    return async (dispatch: ThunkDispatch<{}, {}, AnyAction>): Promise<Action> => {
        try {
            const result = await api.post(`/auth/login`, {username, password});
            return dispatch({type: 'set_user_session', payload: result.data});
        } catch (err) {
            console.log(err);
            throw (err.response && err.response.data) || {code: err};
        }
    }
}

这是执行没有问题,但如果我尝试处理这个:

dispatch(login({username: "admin", password: "adminpassword1"}))
    .then(d => console.log("ok"))
    .catch(err => console.log(err));

我收到此错误:

TS2339: Property 'then' does not exist on type 'ThunkAction   >, {}, {}, AnyAction>'

我试图阅读有关 Redux 中的类型的部分,但我找不到正确的方法来声明这个调度函数可以在我需要的时候工作。

https://redux.js.org/recipes/usage-with-typescript

更糟糕的是,我在执行操作后收到此运行时错误:

Possible Unhandled Promise Rejection (id: 0):

所以承诺就在某处。

1 个答案:

答案 0 :(得分:1)

基本的 Dispatch 类型不知道 thunk。你需要推断出 store.dispatch 的修改类型,它告诉 TS thunk 是可以接受的,然后它就会明白调度 thunk 实际上返回了一个 promise。

这里最好的选择是切换到使用我们官方的 Redux Toolkit 包,并推断 store.dispatch 的类型,如下所示:

https://redux-toolkit.js.org/tutorials/typescript

然后,您可以将改进的 Dispatch 类型与 useDispatch 挂钩一起使用。

(FWIW,重做 Redux 核心文档“与 TS 一起使用”页面在我近期的待办事项列表中)