const sampleSchema= z.object({
sampleData: z.array(
z.object({
flag: z.boolean(),
value: z.number()
})
),
});
type FormInput = z.input<typeof sampleSchema>;
const SampleComponent = () => {
const { control } = useFormContext<FormInput>();
const { field } = useController({ control, name: 'sampleData' });
return (
<input
onChange={(event) => {
field.onChange([
...field.value,
...[
{
flag: true,
// does not have value
},
],
]);
}}
/>
);
};
In the schema, value is defined as not nullish, but it is not type checked because field.onChange() expects any[]
- Is it possible to pass explicit type to onChange?
- If this is not possible, is it possible to use eslint etc. to detect code that uses the Spread Operator to combine different types into one array as an error?
Directly passing an explicit type to onChange is not supported out of the box because onChange is meant to handle any user input. However, you can enforce type checking indirectly by defining a type-safe wrapper function around your logic before calling onChange. Here's an example: