类型安全 useDispatch 与 redux-thunk

K. *_* D. 10 typescript redux redux-thunk

我正在redux-thunk使用异步操作创建器。结果也返回给相应的调用者。

function fetchUserName(userId: number): Promise<string> {
  return Promise.resolve(`User ${userId}`)
}

function requestUserName(userId: number) {
  return (dispatch: Dispatch) => {
    return fetchUserName(userId).then(name => {
      dispatch({
        type: 'SET_USERNAME',
        payload: name,
      })
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

这样,存储被更新,同时允许组件直接处理响应。

function User() {
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(requestUserName(1))
      .then(name => {
        console.log(`user name is ${name}`)
      })
      .catch(reason => {
        alert('failed fetching user name')
      })
  }, [])
}
Run Code Online (Sandbox Code Playgroud)

这是按预期工作的,但由于类型无效,它不会被 TypeScript 编译。

  1. dispatch由归国useDispatch不被识别为一个返回无极等打字稿认为,一个功能Property 'then' does not exist on type '(dispatch: Dispatch<AnyAction>) => Promise<void>'.
  2. 即使它会被识别,也应该正确键入 Promise

这种情况如何解决?

对我来说,创建一个包装器useDispatch或重新定义类型是dispatch完全没问题的,但我不知道在这种特定情况下该类型应该是什么样子。

非常感谢您的任何建议。

for*_*d04 22

useDispatch返回Redux 使用Dispatch类型,因此您只能使用它调度标准操作。要也分派 thunk 操作,请将其类型声明为(from )。ThunkDispatchredux-thunk

ThunkDispatch接收商店状态的类型参数、额外的 thunk 参数和您的操作类型。它允许调度 a ThunkAction,它基本上是requestUserName.

例如,您可以这样输入:

import { ThunkDispatch } from "redux-thunk";
import { AnyAction } from "redux";

type State = { a: string }; // your state type
type AppDispatch = ThunkDispatch<State, any, AnyAction>; 
// or restrict to specific actions instead of AnyAction

function User() {
  const dispatch: AppDispatch = useDispatch();
  useEffect(() => {
    dispatch(requestUserName(1))
      .then(...)  // works now
  }, []);
  ...
}
Run Code Online (Sandbox Code Playgroud)

AppDispatch也可以从 store推断typeof store.dispatch

import thunk, { ThunkDispatch, ThunkMiddleware } from "redux-thunk";

const mw: ThunkMiddleware<State, AnyAction> = thunk;
const dummyReducer = (s: State | undefined, a: AnyAction) => ({} as State);
const store = createStore(dummyReducer, applyMiddleware(mw));

type AppDispatch = typeof store.dispatch // <-- get the type from store
Run Code Online (Sandbox Code Playgroud)

TS 游乐场示例