Starting from my interview, then the contract, insurance policies, and documents, everything was in French in my case. It’s not surprising to experience a full French meeting, phone call, or email…


独家优惠奖金 100% 高达 1 BTC + 180 免费旋转

How to add types to your local storage

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:

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.

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!

Add a comment

Related posts:

Entre el cielo y la tierra

Lucas Ocampos cae dentro del área y el árbitro chileno Roberto Tobar cobra penal para la Selección Argentina. Está Lionel Messi en cancha, sin embargo, la estrella del Sevilla cree tener los avales…

Blame It On The Texas Sky

Chelsea said to me one night,. “Blame It On The Texas Sky” is published by Max Mundan.

Teeth and Gum Care Tips to Protect Your Dental Health

Like your physical health, you also need to adopt healthy practices to protect your teeth and gums. Other than the cliché advice to brush your teeth twice every day and to schedule a dentist visit…