【问题标题】:Typescript, object is possibly undefined inside null check打字稿,对象可能在空检查中未定义
【发布时间】:2021-08-08 09:00:34
【问题描述】:

我想知道,这段代码如何给出object is possibly undefined error

  if (newFocus) {
    if (viewCache[viewId] !== undefined) {
      dispatch(ViewActions.focusOn(viewCache[viewId].focus));
    } else {
      dispatch(ViewActions.focusOn(newFocus));
    }
  }

第 3 行给了我错误,viewCache[viewId] is possibly undefined 即使包裹在 if (viewCache[viewId] !== undefined)

【问题讨论】:

    标签: typescript undefined null-check


    【解决方案1】:

    错误似乎指出viewCache 可以是undefined。您也可以添加对其存在的检查

    if (newFocus) {
        if (viewCache && viewCache[viewId] !== undefined) {
          dispatch(ViewActions.focusOn(viewCache[viewId].focus));
        } else {
          dispatch(ViewActions.focusOn(newFocus));
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2021-01-19
      • 2019-07-30
      • 1970-01-01
      • 2019-12-24
      • 2019-09-15
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      相关资源
      最近更新 更多