How to add types to your local storage

Giovanni Cascio
2 min readOct 11, 2020

--

Photo by Tom Fisk from Pexels

With HTML5 browsers introduced the Storage API — a key value storage that stores data in the browser without the need of cookies — with the two implementations localStorage and sessionStorage.

The browsers Storage API can come in very handy but has its limitations:

  • We can only store strings, this means we have to stringify everything but strings.
  • When using TypeScript, we have no typings.

To make our life a bit easier at lyno - a virtual presence tool - we built a little wrapper for the Storage API which tackles these limitations. In the following sections we will have a look at the basic approach

Stringify and parse

As mentioned we can only store strings, so if we want to store anything else we need to store its string representation. Fortunately, the browser’s JSON object does this for us; all we need to do is to wrap the getter and setter method of the Storage API. One approach would be to write to helper functions which handle this:

This was the easy part which you might have already used in some way or another.

Introducing types

So, we would like to have typings while working with the local storage to actually leverage the advantages of using TypeScript. The approach used here defines a schema which represents the storage and acts as a single source of truth. To achieve our goal, we will also make use of generics. As a quick reminder, generics make it possible to create code components that work over a variety of types rather than a single one.

We define a schema as an interface in which we describe the desired structure of the storage:

Next we need getters and setters which will only accept keys and values defined in our schema. As mentioned we use generics to achieve this:

That’s it, we can now access the local storage in a typesafe way!

Yes, there is a package

You can find a more complete example here which is a package I wrote in context of the virtual presence tool lyno. I hope this will improve your developer experience and look forward to receive feedback!

--

--