首页 > 解决方案 > 使用 Redux 调度操作获取 TS 错误,“类型上不存在属性”

问题描述

我有以下 redux-thunk 动作:

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"
});

我像这样发送动作:

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 知道调度操作的期望类型?

优雅的 yalow essnz?

标签: javascriptreactjstypescript

解决方案


我不认为 dispatch() 返回任何东西。Dispatch 只是将操作发送到减速器,您将在其中读取操作的有效负载。

如果您需要 thunk 中的值,您应该在 thunk 中触发一个新操作并在 reducer 中处理它。

要读取反应组件中的值,您还应该使用 useSelector 从您的状态中读取特定值。

如果我知道你试图用价值做什么,会更容易解释。

用 typescript看一下redux
或者考虑使用Redux 工具包来减少使用 Typescript 的样板代码。


推荐阅读