Typed test snapshots
A test needs a strongly typed store snapshot.
Zustand · Type Alias
ExtractState derives a Zustand store’s complete state-and-actions type for reuse. It avoids manually redefining the store type in tests, utilities, or component props.
ExtractState derives the complete state-and-actions type from a Zustand store, so the type can be reused without manually duplicating the store shape.
ExtractState<typeof store>| Name | Type | Description |
|---|---|---|
Store | typeof useBearStore | The Zustand store whose complete state-and-actions type should be extracted. |
The full inferred type of the supplied store's state and actions.
ExtractState is provided by Zustand as a built-in TypeScript utility.ExtractState when the inferred store type is needed outside the declaration where the state is created.import { create, type ExtractState } from 'zustand'
export const useBearStore = create((set) => ({
bears: 3,
food: 'honey',
increase: (by: number) => set((state) => ({ bears: state.bears + by })),
}))
export type BearState = ExtractState<typeof useBearStore>
const snapshot: BearState = useBearStore.getState()
console.log(snapshot.bears)The extracted type can describe a snapshot returned by the store's getState method.
A test needs a strongly typed store snapshot.
A utility function accepts or transforms store data.
A component property should match the store shape.
ExtractState provide?ExtractState is a Zustand TypeScript helper that derives the full type associated with a store. With ExtractState<typeof useBearStore>, the resulting type includes both state fields and action functions.
Follow-up: How can the derived type be used outside React? Use it for utility functions, component props, or typed snapshots obtained from the store API.
ExtractState normally applied?Pass the store value's type with typeof, rather than manually recreating the state interface: ExtractState<typeof useBearStore>. This keeps consumers aligned with the store declaration.
Follow-up: What problem does this avoid? It prevents a separately maintained type from drifting away from the actual store state and actions.
The helper is useful when state typing must be reused outside the original state declaration. The documentation specifically presents tests, utility functions, and component props as use cases.
Follow-up: How would a test use it? Type a snapshot variable as the extracted type before assigning useBearStore.getState().
createuseStoregetStateExtracting Types