Next.js Discord

Discord Forum

How do i get errors from react-hook-form for union types

Unanswered
Weevil parasitoid posted this in #help-forum
Open in Discord
Weevil parasitoidOP
I'm working with a Zod schema and a useForm instance, but I'm struggling to get TypeScript errors for attributes inside the questions field. While I do see errors at runtime, there are no type errors during compile time.

const schema = z.object({
  title: z.string().nonempty(),
  aiContext: z.string().nonempty(),
  questions: z.union([
    z.object({
      type: z.literal(QUESTION_TYPES.RADIO),
      options: z
        .array(
          z.object({
            label: z.string().nonempty(),
          })
        )
        .nonempty(),
    }),
    z.object({
      type: z.literal(QUESTION_TYPES.CHECKBOX),
      options: z
        .array(
          z.object({
            label: z.string().nonempty(),
          })
        )
        .nonempty(),
    }),
    z.object({
      type: z.literal(QUESTION_TYPES.INPUT),
      placeholder: z.string().nonempty(),
    }),
    z.object({
      type: z.literal(QUESTION_TYPES.FILE),
    }),
  ]),
});

type TInput = z.input<typeof schema>;
type TOutput = z.output<typeof schema>;

interface AddQuestionProps {
  lessonId: string;
  refetch: VoidFunction;
}

const AddQuestion: React.FC<AddQuestionProps> = ({ lessonId, refetch }) => {
  const form = useForm<TInput>({
    resolver: zodResolver(schema),
    criteriaMode: "all",
    values: {
      title: "",
      aiContext: "",
      questions: {
        type: "input",
        placeholder: "",
      },
    },
  });
...

1 Reply

Weevil parasitoidOP
ok