为什么我的 reducer 参数类型接受 `undefined`?

Why does my reducer parameter type accepts `undefined`?

我在 react/redux 应用程序中使用 typescript。有一个我不明白的类型错误。

下面是我的操作代码:

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

下面是我的减速器:

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

问题与 handleActions 中的 payload 类型有关。它的类型是ProductActionProps | undefined。我必须检查函数体中的 payload 是否为 undefined。但是我不明白为什么类型接受undefined

{ payload } 的类型应该是{ ProductActionProps },你说得对。我想知道您为 redux-actions 安装的类型定义。

如果您还没有安装 redux-actions 类型声明。

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

然后重启你的编辑器(为了重启TypeScript语言服务)。

如果仍然不起作用,您可能需要升级您的类型。我使用的 "@types/redux-actions": "^2.6.1" 不会重现您的错误。