Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting TS error with Redux dispatch action, `Property does not exist on type`

I have the following 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"
});

And I dispatch the action like this:

const { someString } = dispatch(someAction());

which throws the error,

const { someString } = dispatch(someAction());
        ^^^^^^^^^^
Property 'someString' does not exist on type 'TThunkAction<void, IState, unknown, Action<string>>'

I've tried casting the result like this,

const { someString } = dispatch<TReturnValue>(someAction());

And I've tried redefining TThunkAction, but nothing worked.

How can I get Typescript to know what type to expect from the dispatch action?

gracious-yalow-essnz?

like image 566
Mike K Avatar asked Oct 14 '22 22:10

Mike K


1 Answers

I don't think dispatch() returns anything. Dispatch is just to send the action to the reducers where you would read the payload of the actions.

If you need a value from your thunk you should fire a new action inside the thunk and handle that it in the reducer.

To read the value in your react component you should also be using useSelector to read specific values from your state.

Would be easier to explain if I knew what you where trying to do with the value.

Take a look at redux with typescript.
Or consider Redux toolkit for less boilerplate code with Typescript.

like image 144
Mellet Avatar answered Oct 21 '22 13:10

Mellet