如何在typescript中使动作有效载荷永不被定义

时间:2019-04-24 02:26:48

标签: reactjs typescript redux

在react / redux应用程序中,我在减速器中使用handleActions。 reducer中的代码如下:

export const servicesReducer = handleActions<RootState.ServicesState, string>({
  [ServiceActions.Type.FILTER_SERVICE_SEARCH]: (state, action) => {
    if (action.payload) {
      const payload: string = action.payload;
      const filteredServices = state.all.filter((s: ServiceModel) => s.text.startsWith(payload));
      return {...state, filtered: filteredServices};
    }
    return {...state, filtered: state.all};
  }
},
  initialState);

我遇到的问题是操作中的payload类型是可选的(string | undefined)。因此,我必须为此添加if检查。我想知道如何才能使它永远不再undefined

下面是操作代码。我是否需要对动作功能进行任何更改?如果需要怎么办?

import { createAction } from 'redux-actions';


export namespace ServiceActions {
  export enum Type {
    FILTER_SERVICE_SEARCH = 'FILTER_SERVICE_SEARCH',
  };
  export const filterService = createAction(Type.FILTER_SERVICE_SEARCH);
};

export type ServiceActions = Omit<typeof ServiceActions, 'Type'>;

如何在有效负载上添加类型以使其不为undefined?例如,当我将变量声明为const a:string = ""时,a不能为undefined。我可以为有效载荷做类似的事情吗?

0 个答案:

没有答案