Better Programming

Advice for programmers.

Follow publication

Member-only story

Creating LocalStorage Wrapper With TypeScript

Oleh Zaporozhets
Better Programming
Published in
3 min readNov 16, 2020
Code on a laptop
Photo by Christopher Gower on Unsplash.

Today’s article will be useful for front-end developers who want their code to be type-safe and more readable. I would like to show you how you can wrap different browser APIs to have better control of the situation. For instance, I will use localStorage.

Quick Refresh

LocalStorage is browser storage that is used to store data across browser sessions. It isn’t a big deal to work with localStorage. It has a pretty simple interface:

OK, you may ask, “Why do we need any wrapper at all since it has such a simple interface?” Good point, but the wrapper actually helps us to cover some other part of development rather than simple usability.

Advantages

  • The first advantage is that it will be much easier to implement tests. You have a wrapper that uses the real API in production and a dummy one while testing. Different simulations can be done and a variety of weak spots can be found.
  • It will bring you a single place where you define the names of keys. This means that you won’t save data to a different key accidentally or try to get data from an unexisting key.
  • One more advantage: If you need to rename your key for some reason (e.g. token_v1 to token_v2), it can be done in your wrapper.
  • Last but not least, it’s considered good practice to write your own wrappers on environment APIs.

Developing

So, it should be an abstract class with a generic (I will explain what it is for a little bit later):

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (1)

Write a response