我有以下 redux-thunk Action :
import { Action } from "redux";
import { ThunkAction as ReduxThunkAction } from "redux-thunk";
import { IState } from "./store";
type TThunkAction = ReduxThunkAction<void, IState, unknown, Action<string>>;
export type TReturnValue = { someString: string };
export const someAction = (): TThunkAction => (dispatch): TReturnValue => ({
someString: "some value"
});
我像这样发送 Action :const { someString } = dispatch(someAction());
引发错误,const { someString } = dispatch(someAction());
^^^^^^^^^^
Property 'someString' does not exist on type 'TThunkAction<void, IState, unknown, Action<string>>'
我试过像这样转换结果,const { someString } = dispatch<TReturnValue>(someAction());
我已经尝试重新定义 TThunkAction
,但没有任何效果。我怎样才能让 Typescript 知道调度操作的期望类型?
最佳答案
我不认为 dispatch() 返回任何东西。
Dispatch 只是将操作发送到 reducer ,您将在其中读取操作的有效负载。
如果您需要 thunk 中的值,您应该在 thunk 中触发一个新操作并在 reducer 中处理它。
要读取 react 组件中的值,您还应该使用 useSelector 从您的状态中读取特定值。
如果我知道您在哪里尝试使用该值,会更容易解释。
看看redux with typescript .
或考虑Redux toolkit使用 Typescript 减少样板代码。
关于javascript - 使用 Redux 调度操作获取 TS 错误, `Property does not exist on type`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66086422/