It's weird. I find localstorage.getItem's type in lib.dom.d.ts returns 'string | null', but when I use it in my app it always return string Why?
Description. The keys and the values stored with localStorage are always in the UTF-16 string format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings. localStorage data is specific to the protocol of the document.
The getItem() method of the Storage interface, when passed a key name, will return that key's value, or null if the key does not exist, in the given Storage object.
The GetItem operation returns a set of attributes for the item with the given primary key. If there is no matching item, GetItem does not return any data and there will be no Item element in the response.
The localStorage API uses the getItem method to retrieve data. The method takes a single argument that is the key to the data. If the data is not found, the method returns null .
Because that is how it is:
The keys and the values are always strings
See the doc: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
If you use json object in the localStorage
then you can use JSON.stringify()
and JSON.parse()
method .
To store object in localStorage ,
localStorage.setItem('token', JSON.stringify(user));
To get object from localStorage ,
user = JSON.parse(localStorage.getItem('user'));
Here , you will get the object rather than string .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With