Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A typed LocalStorage interface - with two versions
// With a normal object type
type LocalStorage = {
user: {
email: string
age: number
}
company: {
name: string
}
}
const typedLocalStorage = {
setItem: <T extends keyof LocalStorage>(key: T, value: LocalStorage[T]) => {
localStorage.setItem(key, value ? JSON.stringify(value) : undefined)
},
getItem: <T extends keyof LocalStorage>(key: T): LocalStorage[T] | undefined => {
const value = localStorage.getItem(key)
if (value) {
return JSON.parse(value) as LocalStorage[T]
} else {
return undefined
}
}
}
typedLocalStorage.setItem('user', { email: 'a', age: 2 })
const user: LocalStorage['user'] | undefined = typedLocalStorage.getItem('user')
// With a discriminated union type
type LocalStorage =
| { key: 'user', value: { email: string, age: number } }
| { key: 'company', value: { name: string } }
const typedLocalStorage = {
setItem: <T extends LocalStorage['key']>(key: T, value: Extract<LocalStorage, { key: T, value: unknown }>['value']) => {
localStorage.setItem(key, value ? JSON.stringify(value) : undefined)
},
getItem: <T extends LocalStorage['key']>(key: T): Extract<LocalStorage, { key: T, value: unknown }>['value'] | undefined => {
const value = localStorage.getItem(key)
if (value)
return JSON.parse(value)
else
return undefined
}
}
typedLocalStorage.setItem("company", { name: 'AB' })
const company: { name: string } | undefined = typedLocalStorage.getItem("company")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.