【问题标题】:Property id does not exist on type 'never'“从不”类型上不存在属性 ID
【发布时间】:2018-03-09 02:32:44
【问题描述】:

我正在尝试使用 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;
      }
    })

提前致谢!

【问题讨论】:

    标签: typescript redux reducers


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

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

      理想情况下,您应该向参数添加更具体的类型,以便 TypeScript 可以帮助您捕获错误(您怎么知道 action 具有 type 属性?)。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-18
        • 2021-11-24
        • 2019-12-01
        • 2022-07-21
        • 2017-10-24
        • 2019-10-11
        • 2021-10-14
        • 2021-12-30
        相关资源
        最近更新 更多