Skip to content

Commit

Permalink
feat(types): Make ExtractState public (#2935)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
vorant94 and dai-shi authored Jan 7, 2025
1 parent 929b547 commit d2ac820
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
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
Expand Up @@ -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]
Expand Down

0 comments on commit d2ac820

Please sign in to comment.