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

使用Yup验证Schema时when条件失效,出现TS2769重载匹配错误

Yup条件验证Schema遇到TS2769类型错误的解决方法

问题根源

你在then和otherwise里直接调用string()创建新的Schema实例,导致TypeScript无法识别当前字段的Schema上下文,错误匹配了when的Builder重载签名,而非预期的Keys+Config重载。

修正后的代码

import { object, string } from 'yup';

const formValidationSchema = () => object().shape({
  someInput: string().required('Some error Message'),
  someInput2: string().required('Some error Message 2'),
  someInput3: string().required('Some error Message 3'),
  someInput4: string().when('someInput2', {
    is: 'Some string value',
    // 基于传入的当前schema实例做链式修改
    then: (schema) => schema.optional(),
    otherwise: (schema) => schema.required('Some error Message 4'),
  }),
});

使用箭头函数判断条件的写法

如果需要用动态判断逻辑,给is的参数加上类型注解即可:

someInput4: string().when('someInput2', {
  is: (value: string) => value === 'Some string value',
  then: (schema) => schema.optional(),
  otherwise: (schema) => schema.required('Some error Message 4'),
}),

关键说明

Yup的when方法中,then和otherwise的回调会接收当前字段的Schema实例作为参数,你需要基于这个实例进行链式调整(比如optional()或required()),而非重新创建新的Schema。这样TypeScript就能正确识别类型上下文,匹配到预期的重载签名,解决TS2769错误。

内容的提问来源于stack exchange,提问作者Ellone

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 20:10:07