打字稿,空检查中可能未定义对象

Typescript, object is possibly undefined inside null check

我想知道,这段代码如何给出 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)

错误好像是在指出viewCache可以是undefined。您也可以添加检查其是否存在

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