【问题标题】:What I'm doing wrong in this type checking?我在这种类型检查中做错了什么?
【发布时间】:2021-03-04 23:16:34
【问题描述】:

我有一个打字稿问题需要解决,因为我不是 any 的粉丝。

我收到了这个错误,我已经厌倦了尝试修复它,我不知道我应该如何处理 atm。 这个错误在我的reducer里面,就是:

const dieselReducer = (state = initialState, action: DieselActionTypes): Diesel => {
  switch (action.type) {
    case GET_DIESEL:
      return getDiesel(state, action);
    case GET_DIESEL_SUCCESS:
      return getDieselSuccess(state, action);
    case GET_DIESEL_FAILURE:
      return getDieselFailure(state, action);
    default:
      return state;
  }
};

这是我的getDieselSuccess 函数:

const getDieselSuccess = (state: Diesel, action: GetDieselSuccess) => {
  return {
    ...state,
    loading: false,
    diesels: action.payload.map(item => ({
      value: { ...item },
      label: item.descricao,
    })),
  };
};

这是我的types.ts

export interface ValueProps {
  associated: boolean;
  id: string;
  name: string;
  porto: boolean;
}

export interface DieselProps {
  value: ValueProps;
  label: string;
  descricao: string;
}

export interface Diesel {
  diesels: DieselProps[];
  loading: boolean,
  error: {};
}

export interface GetDieselSuccess {
  type: typeof GET_DIESEL_SUCCESS;
  payload: DieselProps[];
}

最后,这就是我从后端接收数据的方式(转换后如getDieselSuccess 函数所示:

[
  {
    "id": "afdc4808-fc1d-47bf-ee8013b058a4",
    "descricao": "ANP",
    "premissasContratuais": []
  },
  {
    "id": "5c06e835-cdfb-4ae9-e8e9d255dc85",
    "descricao": "ANP Est",
    "premissasContratuais": []
  }
]

抱歉,话题太长了,谁能帮帮我?

【问题讨论】:

    标签: reactjs typescript react-redux react-typescript


    【解决方案1】:

    您的getDieselSuccess 函数应该返回一个Diesel 对象,该对象应该包含一个diesels 属性,而该属性应该包含一个缺少的descricao 属性。

    因此,您的功能应该是:

    const getDieselSuccess = (state: Diesel, action: GetDieselSuccess) => {
      return {
        ...state,
        loading: false,
        diesels: action.payload.map(item => ({
          value: { ...item },
          label: item.descricao,
          descricao: 'YOU-NEED-A-VALUE-HERE' /* Add this prop */
        })),
      };
    };
    

    甚至更好(因为action.payload 似乎属于DieselProps[] 类型)

    const getDieselSuccess = (state: Diesel, action: GetDieselSuccess) => {
      return {
        ...state,
        loading: false,
        diesels: action.payload,
      };
    };
    

    【讨论】:

      猜你喜欢
      • 2019-12-07
      • 2018-12-29
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多