“never”

时间:2017-09-27 14:36:02

标签: typescript redux reducers

我正在尝试使用Typescript在Redux中的状态数组中执行.map函数,问题是它正在抛出错误

  

[ts]'never'

类型中不存在属性'id'

landing.id if语句中,因为它是一个对象数组,代码对我来说很有意义但似乎我错过了那里

export default function landingReducer (state = [], action) {
switch(action.type) {
  case ActionTypes.ADD_LANDING:
    return [...state, action.landing]
  case ActionTypes.EDIT_LANDING:
    return state.map(landing => {
      if (action.landing.id == landing.id) {
        return landing;
      }
    })

提前致谢!

2 个答案:

答案 0 :(得分:2)

可能是由于state和/或action参数缺少类型。尝试使用适用于TypeScript 2.4+的代码,受此article启发:

interface Landing {
    id: any;
}

enum ActionTypes {
    ADD_LANDING  = "ADD_LANDING",
    EDIT_LANDING = "EDIT_LANDING",
    OTHER_ACTION = "__any_other_action_type__"
}

interface AddLandingAction {
    type: ActionTypes.ADD_LANDING;
    landing: Landing;
}

interface EditLandingAction {
    type: ActionTypes.EDIT_LANDING;
    landing: Landing;
}

type LandingAction =
    | AddLandingAction
    | EditLandingAction;

function landingReducer(state: Landing[], action: LandingAction) {
    switch (action.type) {
        case ActionTypes.ADD_LANDING:
            return [...state, action.landing]

        case ActionTypes.EDIT_LANDING:
            return state.map(landing => {
                if (action.landing.id === landing.id) {
                    return landing;
                }
            });
    }
}

答案 1 :(得分:0)

您的代码缺少括号和其他必要的导入,这使得其他人很难快速reproduce and diagnose

话虽这么说,TypeScript将state参数推断为空数组文字[]的类型,它被认为是never[],这意味着它将始终为空。因此map函数不起作用,因为landing被推断为不可能的值(没有never类型的有效值。)

如果你想修复它,你应该告诉TypeScript可能是哪种类型的数组state。快速解决方法是使其成为any

的数组
... function landingReducer (state: any[] = [], action) ...

理想情况下,您应该为参数添加更多特定类型,以便TypeScript可以帮助您捕获错误(您如何知道action具有type属性?)。

希望有所帮助;祝你好运!

相关问题