mirror of
https://github.com/pmndrs/zustand.git
synced 2025-12-08 19:45:52 +00:00
refactor: Relax types for persist middleware (#2332)
Right now, we're requiring new `StateStorage` implementations to forcefully return `void` from inside `setItem` and `removeItem`. When using a library that returns the set value for `setItem` or `removeItem`, therefore returning a `string`, it causes Typescript to fail, requiring some weird workarounds. For example, when using `localforage` (https://github.com/localForage/localForage) one needs to do what we describe below. Notice the `void` keyword. ```typescript const storage: StateStorage = { ...localForage, setItem: void localForage.setItem.bind(localForage) } ``` Another, longer, alternative is ```typescript const storage: StateStorage = { ...localForage, // Curly braces are required because we need to "return `void`" setItem: (name, value) => { localStorage.setItem(name, value) } } ``` By changing the type implementation to ignore types - using unknown - we can simply use `localforage` - and similar libraries - as if we were using `window.localStorage`
This commit is contained in:
parent
8c1a1f0327
commit
7d2525efdb
@ -6,8 +6,8 @@ import type {
|
||||
|
||||
export interface StateStorage {
|
||||
getItem: (name: string) => string | null | Promise<string | null>
|
||||
setItem: (name: string, value: string) => void | Promise<void>
|
||||
removeItem: (name: string) => void | Promise<void>
|
||||
setItem: (name: string, value: string) => unknown | Promise<unknown>
|
||||
removeItem: (name: string) => unknown | Promise<unknown>
|
||||
}
|
||||
|
||||
export type StorageValue<S> = {
|
||||
@ -19,8 +19,8 @@ export interface PersistStorage<S> {
|
||||
getItem: (
|
||||
name: string,
|
||||
) => StorageValue<S> | null | Promise<StorageValue<S> | null>
|
||||
setItem: (name: string, value: StorageValue<S>) => void | Promise<void>
|
||||
removeItem: (name: string) => void | Promise<void>
|
||||
setItem: (name: string, value: StorageValue<S>) => unknown | Promise<unknown>
|
||||
removeItem: (name: string) => unknown | Promise<unknown>
|
||||
}
|
||||
|
||||
type JsonStorageOptions = {
|
||||
@ -401,7 +401,7 @@ const newImpl: PersistImpl = (config, baseOptions) => (set, get, api) => {
|
||||
)
|
||||
}
|
||||
|
||||
const setItem = (): void | Promise<void> => {
|
||||
const setItem = () => {
|
||||
const state = options.partialize({ ...get() })
|
||||
return (storage as PersistStorage<S>).setItem(options.name, {
|
||||
state,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user