I am looking to to do something similar to the below code, but running into a typescript issue and was wondering if anyone has seen this or solved this?
const common = yup.object().shape({
firstName: yup.string().required(),
});
const person = yup
.object()
.shape({
lastName: yup.string().required(),
})
.concat(common);
Here is the issue that looks like it is based on types. Removing the .concat(common) solves this. In a real life example, the common schema would be concat to multiple schemas
No overload matches this call.
Overload 1 of 2, '(schema: ObjectSchema<Shape<object | undefined, { lastName: string; }>>): ObjectSchema<Shape<object | undefined, { lastName: string; }>>', gave the following error.
Argument of type 'ObjectSchema<Shape<object | undefined, { firstName: string; }>>' is not assignable to parameter of type 'ObjectSchema<Shape<object | undefined, { lastName: string; }>>'.
Types of property 'fields' are incompatible.
Type '{ firstName: Schema<string>; } | undefined' is not assignable to type '{ lastName: Schema<string>; } | undefined'.
Property 'lastName' is missing in type '{ firstName: Schema<string>; }' but required in type '{ lastName: Schema<string>; }'.
Overload 2 of 2, '(schema: ObjectSchema<object>): ObjectSchema<object & { lastName: string; }>', gave the following error.
Argument of type 'ObjectSchema<Shape<object | undefined, { firstName: string; }>>' is not assignable to parameter of type 'ObjectSchema<object>'.
Types of property 'fields' are incompatible.
Type '{ firstName: Schema<string>; } | undefined' is not assignable to type 'object'.
Type 'undefined' is not assignable to type 'object'. TS2769
13 | lastName: yup.string().required(),
14 | })
> 15 | .concat(common);
I appreciate any time people take to look into this or provide a path forward.
add .required() method call.
I think Yup's type definition will add undefined as a intersection type since you didn't specify given object would always be not-null.
so below would be an answer code for your problem:
const common = yup.object().shape({
firstName: yup.string().required(),
}).required(); // <--
const person = yup
.object()
.shape({
lastName: yup.string().required(),
})
.required() // <--
.concat(common);
@async3619 - That worked great. I appreciate the quick response!
Closing out this question :)
Most helpful comment
add
.required()method call.I think Yup's type definition will add
undefinedas a intersection type since you didn't specify given object would always be not-null.so below would be an answer code for your problem: