Typescript,对象可能在空检查中未定义

Typescript,对象可能在空检查中未定义,typescript,undefined,null-check,Typescript,Undefined,Null Check,我想知道,这个代码怎么会给出对象可能是未定义的错误 if (newFocus) { if (viewCache[viewId] !== undefined) { dispatch(ViewActions.focusOn(viewCache[viewId].focus)); } else { dispatch(ViewActions.focusOn(newFocus)); } } 第3行给了我一个错误,viewCache[viewId]可能

我想知道,这个代码怎么会给出
对象可能是未定义的错误

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

第3行给了我一个错误,
viewCache[viewId]可能是未定义的
,即使包装在
if(viewCache[viewId]!==undefined)
中,错误似乎指出
viewCache
可能是未定义的。您也可以为其存在添加一个检查

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