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

React16升18+Yup0.26.6→1.2.0时is属性类型报错求助

Yup 1.2.0 升级后 when 方法语法报错解决方案

问题背景

从 Yup 0.26.6 升级到 1.2.0 版本后,原有的条件验证代码出现类型错误,报错指向is: true部分,提示该属性不存在于ConditionBuilder类型中。

错误代码

import helpers from '../../../Shared/validationHelpers';

const { domainName } = helpers.regEx;

export default Yup.object({
    enabled: Yup.boolean(),
    hostname: Yup.string().when('enabled', {
        is: true,
        then: Yup.string()
            .matches(domainName, 'Please provide a fully qualified domain name')
            .required('You must provide a hostname'),
        otherwise: Yup.string().notRequired(),
    }),
});

报错信息

No overload matches this call.
  Overload 1 of 4, '(keys: string | string[], builder: ConditionBuilder<StringSchema<string, AnyObject, undefined, "">>): StringSchema<string, AnyObject, undefined, "">', gave the following error.
    Argument of type '{ is: boolean; then: Yup.StringSchema<string, Yup.AnyObject, undefined, "">; otherwise: Yup.StringSchema<string, Yup.AnyObject, undefined, "">; }' is not assignable to parameter of type 'ConditionBuilder<StringSchema<string, AnyObject, undefined, "">>'.
      Object literal may only specify known properties, and 'is' does not exist in type 'ConditionBuilder<StringSchema<string, AnyObject, undefined, "">>'.

解决方案

Yup 1.x 版本废弃了旧的is/then/otherwise对象式写法,改用函数式的ConditionBuilder。修正后的代码如下:

import helpers from '../../../Shared/validationHelpers';

const { domainName } = helpers.regEx;

export default Yup.object({
    enabled: Yup.boolean(),
    hostname: Yup.string().when('enabled', (enabled) => {
        return enabled 
            ? Yup.string()
                .matches(domainName, 'Please provide a fully qualified domain name')
                .required('You must provide a hostname')
            : Yup.string().notRequired();
    }),
});

补充说明

  • 函数参数中第一个值就是依赖字段enabled的当前值,直接判断即可
  • 也可以使用更简洁的链式写法,或者在函数内返回对应的Schema
  • 如果需要访问表单其他字段的值,可以使用第二个参数context,比如(enabled, { parent }) => { ... }来获取整个表单对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 23:52:38