zod
zod copied to clipboard
Issue with types? Using refine() with an array results in typescript linting error saying type is missing the message property. However, works in runtime.
Hello, I am using zod as a resolver with react hook form. I have a schema setup as follows:
const mySchema = z.object({
// some other properties
myArray: z.array({
// some properties
})
.min(1)
.max(10)
.refine(
(item) => {
// some validation
},
{
message: "My error message"
}
)
});
When trying to access the error message like below, I get a linting error saying property 'message' does not exist on type. However during runtime there is no error and I can access the message properly.
formState.errors.myArray.message
Any idea on how to resolve this?
Same happens when validating array length without the use of .refine.
Example
someField: z.string().array().min(1, { message: "Custom message" }),
Later in code:
<FormErrorMessage>
{errors.someField?.message} {/* Property 'message' does not exist on type FieldError[] */}
</FormErrorMessage>
even though that's how the error object looks.
Currently I'm using (errors.someField as any)?.message but that seems like a hack.
The example is constructed with Chakra UI & react-hook-form in mind but I guess the error might be similar with other libs.
Currently I'm using (errors.someField as any)?.message but that seems like a hack. The example is constructed with Chakra UI & react-hook-form in mind but I guess the error might be similar with other libs.
If you don't want to use any you can use @ts-expect-error as a workaround for now.
Solution courtesy of bennettdams. Discussion: https://github.com/react-hook-form/react-hook-form/discussions/7111#discussioncomment-2956401
I tried to reproduce this issue but wasn't able to get the error: https://codesandbox.io/s/issue-with-types-using-refine-with-an-array-results-in-typescript-linting-error-z9etol?file=/src/App.tsx
Can you show a full example where this error occurs?
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.