如何使用Yup.string().required().nullable()规避TypeScript类型推断错误?
解决Yup中
required().nullable()组合的类型推断问题 你的问题核心在于Yup的yup.InferType默认对应验证通过后的输出类型,required()会确保验证成功后字段一定是非空字符串,所以推断出的foo类型是string;但你需要的是验证前的输入类型,允许初始值为null/undefined,同时验证阶段强制要求为字符串。
下面是两种无需忽略TypeScript错误的解决方案:
方案一:使用InferInputType获取验证前的输入类型
Yup提供了InferInputType类型工具,专门用于获取验证前允许传入的合法数据类型,它会保留nullable()允许的null/undefined类型,同时required()仅作用于验证逻辑,不会影响输入类型推断:
import * as yup from 'yup'; const mySchema = yup.object({ foo: yup.string().required().nullable(), bar: yup.string().required(), buzz: yup.string().nullable() }); // 使用 InferInputType 定义初始值类型 type MySchemaInputType = yup.InferInputType<typeof mySchema>; const initialValue: MySchemaInputType = { foo: undefined, // 不再报错 bar: '1', buzz: undefined };
方案二:手动扩展推断类型
如果你需要更灵活地控制初始值类型,可以手动扩展InferType的结果,将指定字段的类型改为允许null/undefined:
import * as yup from 'yup'; const mySchema = yup.object({ foo: yup.string().required().nullable(), bar: yup.string().required(), buzz: yup.string().nullable() }); // 获取验证后的输出类型 type MySchemaOutputType = yup.InferType<typeof mySchema>; // 扩展类型,允许foo为null/undefined type InitialValueType = Omit<MySchemaOutputType, 'foo'> & { foo: string | null | undefined; }; const initialValue: InitialValueType = { foo: undefined, // 不再报错 bar: '1', buzz: undefined };
关键说明
yup.InferType等价于yup.InferOutputType,代表验证通过后的数据类型,required()会过滤掉null/undefined,所以推断出的foo是string。yup.InferInputType代表验证前可接受的输入类型,会保留nullable()允许的null/undefined,完全符合你“初始值允许为空,验证时强制必填”的需求,推荐优先使用。
内容的提问来源于stack exchange,提问作者iamaword
相关产品推荐
相关产品推荐

