在TypeScript中为Redux Thunk的调度功能设置正确的类型

时间:2020-09-19 01:20:20

标签: reactjs typescript redux redux-thunk

我有一些Redux Thunk在TypeScript中运行的React代码。

动作:

export interface IAddTodoAction {
    text: string
    type: ADD_TODO
}

export type TodoAction = IAddTodoAction | IToggleTodoAction | IEditTodoAction | IDeleteTodoAction | IToggleAllTodoAction

export const addTodo = (text: string): IAddTodoAction => ({
    text,
    type: ADD_TODO,
})

export const testThunk = (employeeId: number): ThunkAction<void, RootState, unknown, Action<string>> => async (dispatch: Dispatch) => {
    try {
        const asyncResp = await axios.get(`https://jsonplaceholder.typicode.com/todos/${employeeId}`)
        console.log("asyncResp", asyncResp)
        const title = asyncResp.data.title
        console.log("title", title)
        dispatch(addTodo(title))
        // dispatch({ title, type: ADD_TODO })
    } catch (error) {
        console.log(error)
    }
}

mapDispatcherToProps

const mapDispatcherToProps = (dispatch: Dispatch): { addTodo: (text: string) => void } | { testThunk: (employeeId: number) => void } => ({
    addTodo: (text: string) => dispatch(actions.addTodo(text)),
    testThunk: (employeeId: number) => dispatch<any>(actions.testThunk(employeeId)),
})

当我在<any> dispatch内的mapDispatcherToProps调用中使用testThunk作为类型时,代码运行良好。

有人可以告诉我我应该使用哪种正确的类型而不是any

0 个答案:

没有答案