https://github.com/sajmoni/typed-ls
Type-safe local storage
https://github.com/sajmoni/typed-ls
local-storage typesafe typescript
Last synced: 3 months ago
JSON representation
Type-safe local storage
- Host: GitHub
- URL: https://github.com/sajmoni/typed-ls
- Owner: sajmoni
- License: mit
- Created: 2022-02-05T12:33:26.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2024-06-10T20:18:24.000Z (about 1 year ago)
- Last Synced: 2025-02-11T03:34:32.329Z (4 months ago)
- Topics: local-storage, typesafe, typescript
- Language: TypeScript
- Homepage:
- Size: 1.72 MB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
typed-ls
Type-safe local storage## :sparkles: Features
A tiny helper library that creates type-safe `get` and `set` functions for working with local storage
### Why?
- The key is only defined once
- Ensures the same type is used when both getting and setting the value
- Reduces boilerplate### How to use
```ts
import { createStoredValue } from 'typed-ls'const defaultValue = 'en'
export const language = createStoredValue('language', defaultValue)
// language.get() => 'en'
// language.set('jp')
// language.remove()
```The type will be inferred from the default value. If this is not possible (for example if the default value is `undefined` or `[]`) you can explicitly set the type instead:
```ts
export const language = createStoredValue('languages', [])
```## :newspaper: API
```ts
createStoredValue(key: string, defaultPayload: T): StoredValue
``````ts
type StoredValue = {
get: () => T
set: (payload: T) => void
remove: () => void
}
```### key
The local storage key
### defaultPayload
If there is no value in local storage, `get` will return the `defaultPayload` instead
---
## :package: Install
```console
npm install typed-ls
```---
## Local storage not available
If local storage is not available then:
- `get` always returns default values
- `set` and `remove` are no-opsThis can happen if the user has turned off local storage in the privacy setting of their browser