A tiny helper library that creates type-safe get
and set
functions for working with local storage
- The key is only defined once
- Ensures the same type is used when both getting and setting the value
- Reduces boilerplate
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:
export const language = createStoredValue<string[]>('languages', [])
createStoredValue<T>(key: string, defaultPayload: T): StoredValue
type StoredValue = {
get: () => T
set: (payload: T) => void
remove: () => void
}
The local storage key
If there is no value in local storage, get
will return the defaultPayload
instead
npm install typed-ls
If local storage is not available then:
get
always returns default valuesset
andremove
are no-ops
This can happen if the user has turned off local storage in the privacy setting of their browser