Missing type inference using TypeScript and Immer following example from Readme #2783
-
Bug DescriptionDescriptionWhen using Immer with Zustand, TypeScript does not catch type errors when setting nested state. The code follows the example from the Zustand documentation, but TypeScript doesn’t detect the type mismatch (state becomes import { produce } from 'immer'
import { create } from 'zustand'
interface MyStore {
aNumber: number
setNumber: () => void
}
const useStore = create<MyStore>()((set) => ({
aNumber: 0,
setNumber: () => set(
produce((state) => {
state.aNumber = "not a number"
}),
),
})) Steps to Reproduce
Expected behaviourTypeScript should detect that "not a number" is a string and raise a type error since the aNumber property is typed as a number. Actual behaviourTypeScript does not raise any errors, allowing the assignment of a string to a number field without warnings. Is this intended behaviour? Reproduction Link |
Beta Was this translation helpful? Give feedback.
Answered by
dbritto-dev
Oct 11, 2024
Replies: 1 comment 1 reply
-
@Duckling92 you are using import { produce } from 'immer'
import { create } from 'zustand'
interface MyStore {
aNumber: number
setNumber: () => void
}
const useStore = create<MyStore>()((set, get) => ({
aNumber: 0,
setNumber: () => set(
produce<ReturnType<typeof get>>((state) => {
state.aNumber = "not a number"
}),
),
})) |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
dbritto-dev
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Duckling92 you are using
produce
fromimmer
directly so you need to take care of typingproduce
, that's not zustand issue