Problem: localStorage isn’t strongly typed


Problem: localStorage isn’t strongly typed. You read and write to it via a string key, and the value returned is always a string. 👎

Solution:
1 Infer types via Zod
2 Wrap localStorage with functions
3 Parse values via Zod

Now the data returned is validated *at runtime*. 🔥

Benefits:
1. The localStorage string key is encapsulated inside one file.

2. If invalid data is in localStorage, the app won't crash. You can quietly ignore it, or log an error if you like.

3. Reading and writing to localStorage is elegant:

View original on X