Fix a return value type of combine (#395)

Co-authored-by: Jaga Apple <jagaapple@uniboar.com>
This commit is contained in:
Jaga Apple 2021-05-22 07:20:22 +09:00 committed by GitHub
parent f2a0efa2e2
commit 8aefb6b1c7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 6 additions and 5 deletions

View File

@ -233,7 +233,7 @@ function Component() {
const scratchRef = useRef(useStore.getState().scratches)
// Connect to the store on mount, disconnect on unmount, catch state-changes in a reference
useEffect(() => useStore.subscribe(
scratches => (scratchRef.current = scratches),
scratches => (scratchRef.current = scratches),
state => state.scratches
), [])
```
@ -457,14 +457,14 @@ const useStore = create<BearState>(set => ({
}))
```
Or, use `combine` and let tsc infer types.
Or, use `combine` and let tsc infer types. This merges two states shallowly.
```tsx
import { combine } from 'zustand/middleware'
const useStore = create(
combine(
{ bears: 0 },
{ bears: 0 },
(set) => ({ increase: (by: number) => set((state) => ({ bears: state.bears + by })) })
),
)

View File

@ -121,6 +121,7 @@ export const devtools = <S extends State>(
return initialState
}
type Combine<T, U> = Omit<T, keyof U> & U
export const combine = <
PrimaryState extends State,
SecondaryState extends State
@ -131,13 +132,13 @@ export const combine = <
get: GetState<PrimaryState>,
api: StoreApi<PrimaryState>
) => SecondaryState
): StateCreator<PrimaryState & SecondaryState> => (set, get, api) =>
): StateCreator<Combine<PrimaryState, SecondaryState>> => (set, get, api) =>
Object.assign(
{},
initialState,
create(
(set as unknown) as SetState<PrimaryState>,
get as GetState<PrimaryState>,
(get as unknown) as GetState<PrimaryState>,
(api as unknown) as StoreApi<PrimaryState>
)
)