Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(types): Make ExtractState public #2935

Merged
merged 4 commits into from
Jan 7, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions docs/guides/typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 1 addition & 2 deletions src/react.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down
2 changes: 2 additions & 0 deletions src/vanilla.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export type ExtractState<S> = S extends { getState: () => infer T } ? T : never

type SetStateInternal<T> = {
_(
partial: T | Partial<T> | { _(state: T): T | Partial<T> }['_'],
Expand Down
Loading