reactjstypescriptreact-reduxredux-actions

Why does my reducer parameter type accepts `undefined`?


I am using typescript in my react/redux app. There is a type error I don't understand.

Below is my action code:

import { createAction } from 'redux-actions';

export enum ProductActionType {
  SEARCH_STAMP = 'SEARCH_STAMP',
  SEARCH_PRODUCT = 'SEARCH_PRODUCT',
};

export interface ProductActionProps {
  text: string;
}

const searchStamp = createAction<ProductActionProps>(ProductActionType.SEARCH_STAMP);

Below is my reducer:

import { handleActions } from 'redux-actions';
import { ProductActionType, ProductActionProps } from '@ap-actions/index';

export const productReducer = handleActions<Product, ProductActionProps>(
  {
    [ProductActionType.SEARCH_STAMP]: (state, { payload }) => { // here why payload type is ProductActionProps | undefined?
      ...
    }
  }, initialState
);

The issue is about the payload type inside handleActions. Its type is ProductActionProps | undefined. I have to check whether payload is undefined in the body of the function. But I don't understand why the type accepts undefined?


Solution

  • You're right that the type of { payload } should be { ProductActionProps }. I am wondering about the type definitions that you have installed for redux-actions.

    If you haven't already, install the redux-actions type declarations.

    npm install @types/redux-actions --save-dev
    

    Then restart your editor (in order to restart the TypeScript language service).

    If that still doesn't work, you might need to upgrade your types. I am using "@types/redux-actions": "^2.6.1" which does not reproduce your error.