Prafull Dhadkar
Prafull Dhadkar

Reputation: 941

How to pass statically typed argument in thunk-action?

In my react app I have created a ThunkAction with the help of Action Creator. It looks like this -

export const oneMoreAsyncThunkAction: ActionCreator< ThunkAction<void, IChatState, {}, ToggleOnlineStateAction >> = (payload: boolean) => {
    return (dispatch: ThunkDispatch<IChatState, {}, ToggleOnlineStateAction >, getState, extraArguement): void => {
      try {        
          const promise = new Promise<ToggleOnlineStateAction>((resolve, reject) =>{
              setTimeout(() => {
                  resolve({
                    type: TOGGLE_ONLINE_STATE,
                    payload: payload
                });
              }, 1000);
          })
          promise.then(action => {
              dispatch(action)
          });
      } catch (e) {}
    };
  };

I am expecting a boolean argument (payload) in my action.

In another file, I am using this action like this -

let action = ChatActions.oneMoreAsyncThinkAction(!props.isOnline);
dispatch(action);

I was expecting that VSCode will suggest me to pass a boolean value as an argument in the action. But it suggests that ...any[] values can be passed in the argument.

enter image description here

I want my Action to be statically typed. How could I fix my code so that VSCode suggest me to pass boolean value in the Action.

Upvotes: 0

Views: 38

Answers (1)

markerikson
markerikson

Reputation: 67489

The simplest answer here is to use the createAsyncThunk API from our official Redux Toolkit package, which is written in TS and strongly typed:

const toggleOnline = createAsyncThunk(
  'chat/toggleOnline',
  async (online: boolean) => {
    await sleep(1000); // use a common util function here
    return online; // becomes the success action payload
  }
)

// later
dispatch(toggleOnline(!isOnline));

Upvotes: 1

Related Questions