Let's overlook the fact that JSON.parse()
has a call signature declaration that returns the unsafe any
type. For now, let's assume that if JSON.parse()
doesn't return null, it will be a value of your expected object type.
There is a possibility that
localStorage.getItem("userData")
could be
null
, and TypeScript considers it an error to call
JSON.parse(null)
because the purpose of
JSON.parse()
is usually to parse strings encoding JSON values. While parsing
null
isn't a runtime error in JavaScript, it's a type error according to TypeScript. Refer to What does "all legal JavaScript is legal TypeScript" mean? for further details.
To make it more type safe, ensure only a string
is passed like this:
const retrievedValue = localStorage.getItem('userData');
const userData = retrievedValue ? JSON.parse(retrievedValue) as {
email: string;
id: string;
_token: string;
_tokenExpirationDate: string;
} : null;
This compiles without errors, and now userData
holds the type {email: string ... } | null
, reflecting the union with the null
type indicating that userData
can be either a valid object or null
.
If you prefer expediency over safety, you can deceive the compiler about the local storage result and assert that it's not null
using the non-null assertion operator (!
):
const userData: {
email: string;
id: string;
_token: string;
_tokenExpirationDate: string;
} | null = JSON.parse(localStorage.getItem('userData')!);
Note that the | null
was manually added since the compiler no longer sees that possibility.
Playground link to code