zod icon indicating copy to clipboard operation
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.

Open ryerrappa opened this issue 3 years ago • 4 comments

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?

ryerrappa avatar Jun 14 '22 06:06 ryerrappa

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.

m-suchorski avatar Jun 27 '22 12:06 m-suchorski

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

ryerrappa avatar Jun 28 '22 23:06 ryerrappa

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?

AustinShelby avatar Jul 03 '22 14:07 AustinShelby

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.

stale[bot] avatar Sep 01 '22 16:09 stale[bot]

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.

stale[bot] avatar Oct 31 '22 17:10 stale[bot]