In the use of similar
JSON.parse(localStorage.getItem(xxxx))
Copy the code
An error is reported when using “, as shown in the figure below:
Reason: The first argument to json. parse must be of type string
But localstorage. getItem can return a string or null
Solutions:
-
Use typeof to check whether the type returned by localStorage.getItem is string
let LOGIN_DATA; let _LOGIN_DATA_KEY = localStorage.getItem(xxxx); if (typeof _LOGIN_DATA_KEY === "string") { LOGIN_DATA = JSON.parse(_LOGIN_DATA_KEY); } Copy the code
-
Add compatibility to json.parse
JSON.parse(localStorage.getItem(xxxx) || '{}'); Copy the code
-
Add type assertion (not recommended) : If localstorage.getitem (XXXX) is indeed a null, an error is reported at runtime
const LOGIN_DATA = JSON.parse( localStorage.getItem(xxxx) as string ); Copy the code