Typescript wrapper class for browser storage

Tired of wrestling with `localStorage` and `sessionStorage` directly? This article presents a neat TypeScript wrapper class to bring some order and consistency to your front-end storage management. Th...

Typescript wrapper class for browser storage

Tired of wrestling with `localStorage` and `sessionStorage` directly? This article presents a neat TypeScript wrapper class to bring some order and consistency to your front-end storage management. The key takeaway is encapsulating the browser's storage API behind a service that handles serialization, deserialization, and key prefixing. This leads to cleaner, more maintainable code when dealing with user settings, application state, or other data you need to persist.

The `StorageService` class, implementing a `StorageServiceInterface`, offers methods like `setItem(key: string, value: T)` and `getItem(key: string): T | null` for type-safe storage. A particularly useful feature is the optional `storagePrefix`. By providing a prefix (like your app's name), you avoid key collisions and can easily manage your application's storage space. The class also includes `removeItem`, `clear`, and `getKeys` methods for comprehensive storage management. The `getKeys` method is particularly handy, allowing you to retrieve all keys associated with your application prefix, with or without the prefix itself. The private `serialize` and `deserialize` methods use `JSON.stringify` and `JSON.parse` to handle the conversion of values to and from strings, as required by `localStorage`.

To use the service, you simply create an instance, like `localStorageService = new StorageService(localStorage, "MY_APP_PREFIX")`. Then, you can store and retrieve data using the type-safe methods: `localStorageService.setItem("user-settings", { theme: "dark", tableLimit: 10 })`. This approach not only provides a cleaner API but also adds a layer of abstraction, making it easier to switch between `localStorage` and `sessionStorage` or even implement custom storage solutions in the future. By abstracting the complexity of browser storage, you can focus on building features rather than wrangling with low-level APIs.


📰 Original article: https://dev.to/muszynov/typescript-wrapper-class-for-browser-storage-55pd

This content has been curated and summarized for Code Crafts readers.