An improved error message would be beneficial in this scenario. The issue lies in the fact that when
window?.sessionStorage?.getItem('accessToken')?
returns
undefined
if the item is not present, your
if
comparison ends up being
undefined | number > number
, which poses a challenge from a type perspective.
To address this, you can simply remove the > 0
part since both undefined
and 0
are considered falsy:
if (window?.sessionStorage?.getItem('accessToken')?.length) {
// Adjusted by removing `> 0`
this.navigateToApplication();
}
Playground link
Alternatively, you can provide a default value using nullish coalescing (??
):
if (window?.sessionStorage?.getItem('accessToken')?.length ?? 0 > 0) {
// Adjusted to include nullish coalescing
this.navigateToApplication();
}
window?.sessionStorage?.getItem('accessToken')?.length ?? 0
will result in
0
when the item is not found, allowing for a valid
number > number
comparison that satisfies TypeScript.
Playground link