mirror of
https://github.com/pmndrs/zustand.git
synced 2025-12-08 19:45:52 +00:00
feat(types): Make ExtractState public (#2935)
* make ExtractState public and move it to vanilla * add docs on the matter * Update vanilla.ts --------- Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>
This commit is contained in:
parent
929b547054
commit
d2ac8205ec
@ -161,6 +161,21 @@ It isn't really a lie because `{ bears: number }` is still a subtype of `{ bears
|
||||
|
||||
Note that we don't use the curried version when using `combine` because `combine` "creates" the state. When using a middleware that creates the state, it isn't necessary to use the curried version because the state now can be inferred. Another middleware that creates state is `redux`. So when using `combine`, `redux`, or any other custom middleware that creates the state, we don't recommend using the curried version.
|
||||
|
||||
If you want to infer state type also outside of state declaration, you can use the `ExtractState` type helper:
|
||||
|
||||
```ts
|
||||
import { create, ExtractState } from 'zustand'
|
||||
import { combine } from 'zustand/middleware'
|
||||
|
||||
type BearState = ExtractState<typeof useBearStore>
|
||||
|
||||
const useBearStore = create(
|
||||
combine({ bears: 0 }, (set) => ({
|
||||
increase: (by: number) => set((state) => ({ bears: state.bears + by })),
|
||||
})),
|
||||
)
|
||||
```
|
||||
|
||||
## Using middlewares
|
||||
|
||||
You do not have to do anything special to use middlewares in TypeScript.
|
||||
|
||||
@ -1,14 +1,13 @@
|
||||
import React from 'react'
|
||||
import { createStore } from './vanilla.ts'
|
||||
import type {
|
||||
ExtractState,
|
||||
Mutate,
|
||||
StateCreator,
|
||||
StoreApi,
|
||||
StoreMutatorIdentifier,
|
||||
} from './vanilla.ts'
|
||||
|
||||
type ExtractState<S> = S extends { getState: () => infer T } ? T : never
|
||||
|
||||
type ReadonlyStoreApi<T> = Pick<
|
||||
StoreApi<T>,
|
||||
'getState' | 'getInitialState' | 'subscribe'
|
||||
|
||||
@ -13,6 +13,8 @@ export interface StoreApi<T> {
|
||||
subscribe: (listener: (state: T, prevState: T) => void) => () => void
|
||||
}
|
||||
|
||||
export type ExtractState<S> = S extends { getState: () => infer T } ? T : never
|
||||
|
||||
type Get<T, K, F> = K extends keyof T ? T[K] : F
|
||||
|
||||
export type Mutate<S, Ms> = number extends Ms['length' & keyof Ms]
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user