'Yup conditional validation in nested object with typescript
I have the following yup validation schema written in typescript:
export const billingAddressStepSchema = yup.object().shape<Partial<BillingAddressStepData>>({
sameAsContractHolder: yup.bool(),
address: yup.
string()
.when("sameAsContractHolder",
{
is: false,
then: yup.string().required("Campo obbligatorio"),
}),
addressNumber: yup.
string()
.when("sameAsContractHolder",
{
is: false,
then: yup.string().required("Campo obbligatorio"),
}),
zipCode: yup.
string()
.when("sameAsContractHolder",
{
is: false,
then: yup.string().required("Campo obbligatorio"),
}),
city: yup.object().when("sameAsContractHolder", {
is: true,
then: yup.object().shape<LookupItem>({
id: yup.string(),
description: yup.string(),
//@ts-ignore
type: yup.string(),
}),
otherwise: yup.object().shape<LookupItem>({
id: yup.string().required("campo obbligatorio"),
description: yup.string().required("campo obbligatorio"),
//@ts-ignore
type: yup.string().required("campo obbligatorio"),
})
})
});
In the form I have to validate with this schema, there is a CheckBox "Same as legal address" that, when is checked, the fields address, addressNumber, zipCode, city must not be required.
The above validation schema works perfectly, my question, in fact, is more related to typescript: for the city field it gives the following error
How can I properly write this rule in order to not have that typescript error?
Many thanks in advance
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

