按Yup文档用ObjectSchema定义验证Schema遇类型不兼容错误
Yup ObjectSchema 类型不匹配问题解决
环境版本
- yup 0.30.0
- @types/yup 0.29.14
问题重现
参照官方文档示例编写类型定义,尝试为Yup校验Schema绑定自定义接口类型,代码如下:
interface TestValidationSchema { title: string; } const validationSchema: Yup.ObjectSchema<TestValidationSchema> = Yup.object({ title: Yup.string().required() }); // Formik中使用 return ( <Formik initialValues={initialValues} onSubmit={handleSubmit} validationSchema={validationSchema} > {/* 表单内容 */} </Formik> );
0.30.0版本报错
Type 'ObjectSchema<Shape<object | undefined, { title: string; }>, object>' is not assignable to type 'ObjectSchema<TestValidationSchema, object>'. Types of property 'fields' are incompatible. Type '{ title: Schema<string, object>; } | undefined' is not assignable to type '{ title: Schema<string, object>; }'. Type 'undefined' is not assignable to type '{ title: Schema<string, object>; }'.
升级至0.32.11版本后报错
Type 'OptionalObjectSchema<{ title: RequiredStringSchema<string | undefined, AnyObject>; }, AnyObject, TypeOfShape<{ title: RequiredStringSchema<string | undefined, AnyObject>; }>>' is not assignable to type 'ObjectSchema<TestValidationSchema, AnyObject, TypeOfShape<TestValidationSchema>, AssertsShape<TestValidationSchema>>'. The types of 'fields.title' are incompatible between these types. Type 'RequiredStringSchema<string | undefined, AnyObject>' is not assignable to type 'string'.ts(2322)
错误原因
- 旧版本(0.30.0):
@types/yup的类型定义中,ObjectSchema的fields属性被标记为可选(可能为undefined),但自定义接口TestValidationSchema要求title必须存在,导致类型不兼容。 - 新版本(0.32.11):Yup重构了类型系统,
ObjectSchema的泛型参数需要的是校验后的值类型,但直接传入自定义接口时,会和Yup内部生成的Schema类型(如RequiredStringSchema)产生冲突——后者包含校验逻辑的类型信息,并非单纯的string类型。
有效解决方案
你找到的以下写法可以正常运行,核心是兼容了Yup类型系统中object可能为undefined的设计:
type ValidationSchema = Yup.ObjectSchema<{ title: string; } | undefined, object>
更推荐的写法是利用Yup自带的InferType工具类型,自动从Schema推导值类型,彻底避免手动定义接口的类型不匹配问题:
// 先定义Schema const validationSchema = Yup.object({ title: Yup.string().required() }); // 自动推导校验后的值类型 type TestValidationSchema = Yup.InferType<typeof validationSchema>; // Formik中直接使用,TS会自动处理类型 return ( <Formik initialValues={initialValues} onSubmit={handleSubmit} validationSchema={validationSchema} > {/* 表单内容 */} </Formik> );
这种写法完全贴合Yup的类型设计逻辑,无需手动对齐类型,也能保证类型安全。
内容的提问来源于stack exchange,提问作者Duderino9000
相关产品推荐
相关产品推荐

