FE / js / ts

Notes on localStorage

Storage interface

Window.localStorage and Window.sessionStorage implement the Storage interface.

Thus, if you need to have a type in ts variable that will contain a localStorage then you can use the Storage interface for that.

let storage:Storage = window.localStorage;

getItem, setItem, removeItem

[Exposed=Window]
interface Storage {
  readonly attribute unsigned long length;
  DOMString? key(unsigned long index);
  getter DOMString? getItem(DOMString key);
  setter undefined setItem(DOMString key, DOMString value);
  deleter undefined removeItem(DOMString key);
  undefined clear();
};

All these methods have strings as arguments.

This is important in case you need to store an object, boolean, number or anything that is not a string as conversion to string is required.

getItem(key) returns null if the key doesn’t exist.

Test if localStorage is available

Modernizr use the following method to detect if the localStorage is available.

var mod = 'modernizr';
try {
  localStorage.setItem(mod, mod);
  localStorage.removeItem(mod);
  return true;
} catch (e) {
  return false;
}