Yup 中最接近模式扩展/继承的方法是使用
object.shape 基于现有架构创建新架构:
Yup documentation
object.shape(fields: object, noSortEdges?: Array<[string, string]>): Schema
定义对象的键和所述键的模式。
请注意,您可以链接 shape 方法,其作用类似于对象扩展
const baseSchema = Yup.object().shape({
id: string().isRequired(),
name: string().isRequired()
})
const someSchema = baseSchema.shape({
id: number().isRequired(),
age: number().isRequired()
})
相当于:
const someSchema = Yup.object().shape({
id: number().isRequired(), // notice how 'id' is overridden by child schema
name: string().isRequired(),
age: number().isRequired()
})
另一种方法是使用concat(schema)通过组合两个schema来创建一个新的schema实例:Yup documentation
mixed.concat(schema: Schema): Schema
通过组合两个架构来创建架构的新实例。只能连接相同类型的模式。
const baseSchema = Yup.object().shape({
name: string().isRequired()
})
const someSchema = baseSchema.concat(
Yup.object().shape({
age: number().isRequired()
}))
// someSchema will be equipped with both `name` and `age` attributes
请注意,concat 仅在两个架构对象具有不同属性或具有完全相同类型的相同属性时才有效。