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

React TypeScript项目中如何通过Yup Schema判断字段是否必填?

解决Yup判断字段必填时的TypeScript类型错误

问题场景

在React TypeScript项目中,想要通过Yup校验Schema判断特定字段是否必填,从而给自定义文本字段组件动态添加required属性,但原代码触发TypeScript类型错误:

Property 'spec' does not exist on type 'Reference | ISchema<string, AnyObject, any, any>'.
Property 'spec' does not exist on type 'Reference'.ts(2339)

原代码示例:

import * as yup from 'yup';

const schema = yup.object().shape({
  name: yup.string().required('Required'),
  email: yup.string(),
});
const isNameRequired = schema.fields['name'].spec?.presence === 'required';

解决方案

问题根源是schema.fields['name']的类型为Reference | ISchema,TypeScript无法确定它不是Reference类型,而spec属性仅存在于ISchema上。以下是三种可行解决方式:

方案1:类型断言

直接将字段断言为yup.ISchema类型,跳过类型检查:

import * as yup from 'yup';

const schema = yup.object().shape({
  name: yup.string().required('Required'),
  email: yup.string(),
});
const nameField = schema.fields['name'] as yup.ISchema;
const isNameRequired = nameField.spec?.presence === 'required';

方案2:类型守卫(更安全)

通过自定义类型守卫先判断字段类型,再访问spec属性:

import * as yup from 'yup';

const schema = yup.object().shape({
  name: yup.string().required('Required'),
  email: yup.string(),
});

function isSchema(field: yup.Reference | yup.ISchema): field is yup.ISchema {
  return 'spec' in field;
}

const nameField = schema.fields['name'];
const isNameRequired = isSchema(nameField) ? nameField.spec?.presence === 'required' : false;

方案3:使用官方API(推荐)

避免依赖Yup内部属性spec,改用官方暴露的describe()方法获取字段校验元数据,兼容性更稳定:

import * as yup from 'yup';

const schema = yup.object().shape({
  name: yup.string().required('Required'),
  email: yup.string(),
});

const schemaDesc = schema.describe();
const isNameRequired = schemaDesc.fields.name?.flags.required ?? false;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 05:19:52