Skip to content

Commit

Permalink
tweaked types in computed.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisvander committed May 21, 2023
1 parent b7b06dd commit b86e1a6
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions src/computed.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { StateCreator, StoreApi, StoreMutatorIdentifier } from "zustand"
import { StateCreator, StoreApi, StoreMutatorIdentifier, Mutate } from "zustand"
import { shallow } from "zustand/shallow"

export type ComputedStateOpts<T> = {
Expand All @@ -18,19 +18,18 @@ export type ComputedStateCreator = <
opts?: ComputedStateOpts<T>
) => StateCreator<T, Mps, [["chrisvander/zustand-computed", A], ...Mcs], T & A>

type Cast<T, U> = T extends U ? T : U
type Write<T, U> = Omit<T, keyof U> & U

type StoreCompute<S, A> = S extends {
getState: () => infer T
}
? Omit<StoreApi<T & A>, "setState">
: never

type WithCompute<S, A> = Write<S, StoreCompute<S, A>>

declare module "zustand" {
interface StoreMutators<S, A> {
"chrisvander/zustand-computed": WithCompute<S, A>
"chrisvander/zustand-computed": WithCompute<Cast<S, object>, A>
}
}

Expand Down Expand Up @@ -95,8 +94,9 @@ const computedImpl: ComputedStateImpl = (f, compute, opts) => {
}, replace)
}

api.setState = setWithComputed
const st = f(setWithComputed, get, api) as T & A
const _api = api as Mutate<StoreApi<T>, [["chrisvander/zustand-computed", A]]>
_api.setState = setWithComputed
const st = f(setWithComputed, get, _api) as T & A
return Object.assign({}, st, compute(st))
}
}
Expand Down

0 comments on commit b86e1a6

Please sign in to comment.