reactjstypescriptreduxredux-actionstypesafe-actions

I'm working to complete redux with typescript. How can I adjust type what I want in these actions


I just tried to use createStandardAction of typesafe-actions. I've understand it's able to set Action, type of payload. But I wanna set actionType in action like number, string, as well using createStandardAction. How can I solve this problem.

import { createStandardAction } from 'typesafe-actions';
import { handleActions } from 'redux-actions';
import { produce } from 'immer';

const COUNT = 'workers/COUNT';
const INCREMENT = 'workers/INCREMENT';


//workersActions.count'type is any
//But I wanna this type is number. 
export const workersActions = {
  count: createStandardAction(COUNT)<number>(),
  increment: createStandardAction(INCREMENT)<void>(),
};

type Increment = ReturnType<typeof workersActions.increment>;

export type WorkerState = {
  count: number;
};

const initialState : WorkerState = {
  count : 0
}
const workers = handleActions<WorkerState, any>(
  {
    [INCREMENT]: (state, action: Increment) => {
      return produce(state, draft => {
        draft.count = action.payload + 1;
      });
    },
  },
  initialState,
);

Solution

  • You can use interface like this.

    types.js

    export const SEND_MESSAGE = 'SEND_MESSAGE'
    export const DELETE_MESSAGE = 'DELETE_MESSAGE'
    
    interface SendMessageAction {
      type: typeof SEND_MESSAGE
      payload: Message
    }
    
    interface DeleteMessageAction {
      type: typeof DELETE_MESSAGE
      meta: {
        timestamp: number
      }
    }
    
    export type ChatActionTypes = SendMessageAction | DeleteMessageAction
    

    actions.ts

    import { Message, SEND_MESSAGE, DELETE_MESSAGE, ChatActionTypes } from './types'
    
    // TypeScript infers that this function is returning SendMessageAction
    export function sendMessage(newMessage: Message): ChatActionTypes {
      return {
        type: SEND_MESSAGE,
        payload: newMessage
      }
    }
    
    // TypeScript infers that this function is returning DeleteMessageAction
    export function deleteMessage(timestamp: number): ChatActionTypes {
      return {
        type: DELETE_MESSAGE,
        meta: {
          timestamp
        }
      }
    }
    

    for more details : https://redux.js.org/recipes/usage-with-typescript#type-checking-state