reactjsuser-interfacenext.jsreact-hook-form

Shadcn - Type 'CheckedState' is not assignable to type 'boolean | ChangeEvent<Element>'


I am encountering an error in my code that uses the shadcn library. The error specifically occurs with the Checkbox onCheckedChange event in the following part of my code:

<FormField
    control={form.control}
    name="remember"
    render={({field}) => (
        <FormItem className="flex flex-row items-start space-x-3 space-y-0.5">
            <FormControl>
                <Checkbox checked={field.value} onCheckedChange={field.onChange}/>
            </FormControl>
            <div className="space-y-1 leading-none">
                <FormLabel className="text-md cursor-pointer select-none">Angemeldet bleiben</FormLabel>
            </div>
        </FormItem>
    )}
/>

The error message I'm getting is:

TS2322: Type '(event: boolean | ChangeEvent<Element>) => void' is not assignable to type '(checked: CheckedState) => void'. Types of parameters 'event' and 'checked' are incompatible. Type 'CheckedState' is not assignable to type 'boolean | ChangeEvent<Element>'. Type '"indeterminate"' is not assignable to type 'boolean | ChangeEvent<Element>'.

Additionally, I am also using react-hook-form and zod for validation, as shown in the following code snippet:

const form = useForm({
    resolver: zodResolver(authSchema),
    defaultValues: {
        email: "john.doe@example.com",
        password: "123456",
        remember: false
    }
});

Could you please help me understand the cause of this error and suggest a possible solution?


Solution

  • Update

    Is seems to be a known issue with ReactHookForm. The current solution is to roll back to react-hook-form@v7.44.3

    Original answer

    I can't replicate your code, but the typescript error suggests that the onCheckedChange handler isn't compatible with the field.onChange event. Firstly, try

    onCheckedChange={event => field.onChange(event.target.checked)}
    

    If that doesn't work because it thinks event could be a boolean, try:

    onCheckedChange={event => {
        const isChecked = typeof event === "boolean" ? event : event.target.checked;
        field.onChange(isChecked);
    }}
    

    This may not be perfect as I can't see what CheckedState should be, but hopefully this will answer your question.