Clomez
Clomez

Reputation: 1512

Typescript, object is possibly undefined inside null check

Im wondering, how is this code giving object is possibly undefined error

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

and line 3 is giving me error, viewCache[viewId] is possibly undefined even when wrapped in if (viewCache[viewId] !== undefined)

Upvotes: 0

Views: 51

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281606

The error seems to be pointing out that viewCache can be undefined. You can add a check for its existence too

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

Upvotes: 1

Related Questions