Home > other >  Object is possibly 'undefined' - on window local storage get Item method
Object is possibly 'undefined' - on window local storage get Item method

Time:07-11

 if (window?.sessionStorage?.getItem('accessToken')?.length > 0) {
  this.navigateToApplication();
}

getting an error as :

Object is possibly 'undefined'.ts(2532)

how to fix this? I am trying to get the value by optional here.

CodePudding user response:

This could use a better error message. :-) The problem is that since window?.sessionStorage?.getItem('accessToken')? evaluates to undefined if the item isn't there, your if comparison is undefined | number > number, which is problematic from a type perspective.

You can just get rid of the > 0 since both undefined and 0 are falsy:

if (window?.sessionStorage?.getItem('accessToken')?.length) {
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^−−− Removed `> 0`
    this.navigateToApplication();
}

Playground link

Alternatively, provide a default value using nullish coalescing (??):

if (window?.sessionStorage?.getItem('accessToken')?.length ?? 0 > 0) {
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^
    this.navigateToApplication();
}

window?.sessionStorage?.getItem('accessToken')?.length ?? 0 will evaluate to 0 if the item isn't there, which makes for a number > number comparison, which TypeScript is happy with.

Playground link

CodePudding user response:

The problem here is that window.sessionStorage.getItem("accessToken") might be undefined. That's why you need to check beforehand if your item exists.

  const accessToken = window.sessionStorage.getItem("accessToken");
  if (accessToken && accessToken?.length > 0) {
    this.navigateToApplication();
  }
  • Related