如何复用并修改Yup Schema字段?解决TS类型报错问题
问题描述
我有如下Yup Schema:
export const schema = yup.object({ id: yup.number().label("ID").positive().integer().required(), name: yup.string().label("name").max(255).required() });
我想复用这个Schema并修改其中的name属性,让它变为notRequired()。原本以为用yup.reach(schema, "name").notRequired()就能实现,但IDE报出TypeScript错误:
Property 'notRequired' does not exist on type 'Reference | ISchema<string, AnyObject, any, any>'. Property 'notRequired' does not exist on type 'Reference'.
解决办法
方法1:用类型断言明确Schema类型
yup.reach返回的类型可能是Reference或ISchema,TypeScript无法确定具体类型,所以可以用类型断言告诉编译器这是一个字符串Schema:
import * as yup from 'yup'; const modifiedName = (yup.reach(schema, "name") as yup.StringSchema).notRequired(); const modifiedSchema = schema.shape({ name: modifiedName });
方法2:直接访问原Schema的fields属性修改
直接从原Schema的fields里拿到name的配置,再修改必填规则:
const modifiedSchema = yup.object({ ...schema.fields, name: schema.fields.name.notRequired() });
方法3:克隆原字段Schema再修改
利用Yup Schema的clone方法复制原字段配置,再调整规则:
const originalNameSchema = schema.fields.name; const modifiedNameSchema = originalNameSchema.clone().notRequired(); const modifiedSchema = schema.shape({ name: modifiedNameSchema });
报错原因
TypeScript中yup.reach的返回类型是Reference | ISchema,而Reference类型并没有notRequired方法,所以编译器会报错。通过上面几种方式明确拿到Schema类型,就能正常调用notRequired方法了。
内容的提问来源于stack exchange,提问作者kamm
相关产品推荐
相关产品推荐

