chrisvander / zustand-computed

A Zustand middleware to create computed states.
MIT License
80 stars 8 forks source link

Typing of get() does not include computed state #15

Closed geirsagberg closed 2 weeks ago

geirsagberg commented 8 months ago

Given the following code:

interface State {
  a: number
  b: number
}

function computeState({ a, b }: State) {
  return {
    c: a + b,
  }
}

const useState = create<State>()(
  computed(
    immer((set, get) => ({
      a: 1,
      b: 2,
      incrementAndLog: () => {
        set((state) => {
          state.a += 1
          state.b += 1
        })
        // Error: Property 'c' does not exist on type 'State'
        const { c } = get()
        console.log(c)
      },
    })),
    computeState
  )
)

Is there a way to make get() automatically include the computed properties?

geirsagberg commented 8 months ago

The code works as expected; property c exists, only the typing does not match. I know I can workaround with get() as unknown as ComputedState but would be nice if this was not necessary.

chrisvander commented 8 months ago

The best way would be to make the root create call (which determines the get() function's typing) be templated with some FullState type, perhaps:

type FullState = State & ReturnType<typeof computeState>
geirsagberg commented 7 months ago

With type FullState = State & ReturnType<typeof computeState> I get errors because create<FullState> expects me to return values for the computed state.

Closest workaround I could find was:

type FullState = State & Partial<ReturnType<typeof computeState>>

Downside of this is that all computed values will be potentially undefined when used in the create call.

chrisvander commented 6 months ago

Hey, @geirsagberg, sorry to take so long to get back to you. Unfortunately, with Immer, Immer derives the type for it's SetState from GetState, and the ComputedStore is explicitly left out of SetState for now. Without Immer, get() has the correct type in version 1.4.0.

chrisvander commented 2 weeks ago

One other suggestion, you could try swapping Immer & computed. Otherwise, closing this issue.

chrisvander commented 2 weeks ago

Hey, figured out the issue. Middleware types were not cascading down appropriately. I would suggest trying out version 2.0 and see if the new pattern brings the types through appropriately. I also opened (#2696)[https://github.com/pmndrs/zustand/pull/2696] to address the aforementioned issue with Immer deriving the setState type from getState. Let me know if that works.