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:
Mordechai Dror 2025-01-07 15:57:18 +02:00 committed by GitHub
parent 929b547054
commit d2ac8205ec
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 18 additions and 2 deletions

View File

@ -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.

View File

@ -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'

View File

@ -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]