使用react-hook-form与yup实现单选按钮条件验证遇TypeScript错误
React Hook Form + Yup 条件验证报错解决
问题根源
你遇到的TypeScript错误是因为Yup v1+ 废弃了旧的when对象式语法,原写法中直接将is设为字符串值的方式不再被支持,TypeScript无法正确推断类型导致报错。
正确的验证Schema写法
写法一:带函数式判断的对象写法
const validationSchema = yup.object({ radioButtons: yup.string().required("Needed"), textInput: yup.string().when("radioButtons", { is: (val: string) => val === "Yes", // 必须返回布尔值的函数 then: (schema) => schema.required("Needed"), // 基于当前schema修改 otherwise: (schema) => schema.notRequired(), }), });
写法二:简洁函数式写法
const validationSchema = yup.object({ radioButtons: yup.string().required("Needed"), textInput: yup.string().when("radioButtons", (val, schema) => val === "Yes" ? schema.required("Needed") : schema.notRequired() ), });
关键注意点
is必须是布尔返回值的函数:Yup v1.x要求is参数为函数,返回true/false,不能直接传字符串,这是解决类型错误的核心。- 复用当前schema:
then和otherwise里直接修改传入的schema,而不是重新创建yup.string(),避免类型不匹配。 - 组件值传递检查:确保你的
RadioGroupInput组件正确将选中的"Yes"/"No"值通过field.onChange传递给React Hook Form,否则条件验证逻辑不会触发。
额外类型优化(可选)
如果TypeScript仍有类型提示问题,可以显式指定表单数据类型:
const validationSchema = yup.object<FirstPageFormData>({ radioButtons: yup.string().required("Needed"), textInput: yup.string().when("radioButtons", (val, schema) => val === "Yes" ? schema.required("Needed") : schema.notRequired() ), });
内容的提问来源于stack exchange,提问作者Squizzi3
相关产品推荐
相关产品推荐

