如何使用 redux-thunk 和 TypeScript 调度 ThunkAction

use*_*345 1 typescript redux redux-thunk

我在使用 Typescript 调度 redux-thunk 操作时遇到问题。

import { AnyAction, applyMiddleware, createStore } from 'redux'
import thunk, { ThunkAction } from 'redux-thunk'

interface State {
  counter: number
}

const initialState: State = {
  counter: 10
}

function reducer(state = initialState, action: AnyAction) {
  switch (action.type) {
    case 'increment':
      return { counter: action.payload }
    default:
      return state
  }
}

function increment(): ThunkAction<void, State, unknown, AnyAction> {
  return async function (dispatch) {
    dispatch({
      type: 'increment',
      payload: 20
    })
  }
}

const store = createStore(reducer, applyMiddleware(thunk))

store.dispatch(increment())

Run Code Online (Sandbox Code Playgroud)

这是我收到的错误:

Argument of type 'ThunkAction<void, State, unknown, AnyAction>' is not assignable to parameter of type 'AnyAction'.
  Property 'type' is missing in type 'ThunkAction<void, State, unknown, AnyAction>' but required in type 'AnyAction'.
Run Code Online (Sandbox Code Playgroud)

我已经尝试了多种不同的动作类型,例如自定义界面、动作等,但没有任何效果。

phr*_*hry 5

默认dispatch类型不知道 thunk,因为“基本 redux”类型不是很强大。因此,您必须手动将其转换为 ThunkDispatch:

(store.dispatch as ThunkDispatch<State, unknown, AnyAction>)(increment())
Run Code Online (Sandbox Code Playgroud)

就像 PSA:您在这里编写的 redux 类型(带有手写操作、操作类型、switch-case 语句和 reducer 中的不可变逻辑的 vanilla redux)不再是编写 redux 的“官方推荐方法”。请查看redux toolkit并最好遵循官方的、最新的redux 教程,因为您很可能遵循的是一个非常过时的教程

终极版工具包也是很多更容易使用一般,并特意用打字稿(和store.dispatch如果你使用它会有正确的类型;))