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

时间:2019-06-11 11:58:04

标签: reactjs typescript react-redux redux-actions

我在我的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
);

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

1 个答案:

答案 0 :(得分:0)

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

如果尚未安装redux-actions类型声明。

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

然后重新启动编辑器(以重新启动TypeScript语言服务)。

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