You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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()
  ),
});

关键注意点

  1. is必须是布尔返回值的函数:Yup v1.x要求is参数为函数,返回true/false,不能直接传字符串,这是解决类型错误的核心。
  2. 复用当前schema:then和otherwise里直接修改传入的schema,而不是重新创建yup.string(),避免类型不匹配。
  3. 组件值传递检查:确保你的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 19:36:01