fix(types): assume getState and setState will always exist on the store (#1371)

* fix(types): assume `getState` and `setState` will always exist on the store

* run prettier

* make fallback in `Get` required
This commit is contained in:
Devansh Jethmalani 2022-10-23 04:12:55 +05:30 committed by GitHub
parent d27ea94884
commit b36f29af30
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 4 deletions

View File

@ -12,7 +12,7 @@ export interface StoreApi<T> {
destroy: () => void
}
type Get<T, K, F = never> = K extends keyof T ? T[K] : F
type Get<T, K, F> = K extends keyof T ? T[K] : F
export type Mutate<S, Ms> = number extends Ms['length' & keyof Ms]
? S
@ -28,8 +28,8 @@ export type StateCreator<
Mos extends [StoreMutatorIdentifier, unknown][] = [],
U = T
> = ((
setState: Get<Mutate<StoreApi<T>, Mis>, 'setState', undefined>,
getState: Get<Mutate<StoreApi<T>, Mis>, 'getState', undefined>,
setState: Get<Mutate<StoreApi<T>, Mis>, 'setState', never>,
getState: Get<Mutate<StoreApi<T>, Mis>, 'getState', never>,
store: Mutate<StoreApi<T>, Mis>,
$$storeMutations: Mis
) => U) & { $$storeMutators?: Mos }

View File

@ -1,4 +1,10 @@
import create, { StateCreator, StoreApi, UseBoundStore } from 'zustand'
import create, {
StateCreator,
StoreApi,
StoreMutatorIdentifier,
UseBoundStore,
} from 'zustand'
import { persist } from 'zustand/middleware'
it('can use exposed types', () => {
type ExampleState = {
@ -188,3 +194,22 @@ it('state is covariant', () => {
baz: string
}> = store
})
it('StateCreator<T, [StoreMutatorIdentfier, unknown][]> is StateCreator<T, []>', () => {
interface State {
count: number
increment: () => void
}
const foo: <M extends [StoreMutatorIdentifier, unknown][]>() => StateCreator<
State,
M
> = () => (set, get) => ({
count: 0,
increment: () => {
set({ count: get().count + 1 })
},
})
create<State>()(persist(foo()))
})