I added react hook form in react app, while validating certain fields i add some condition in schema.
yup
.object({
test1: yup.number().when('test2', (test2: number, schema: yup.NumberSchema): yup.NumberSchema => {
if (test2 !== undefined && test2 < 1) {
return schema.required('Required Field').min(0).max(100).typeError('Please enter test1')
}
return schema.notRequired()
}),
Name: yup
.string()
.trim()
.required('Required Field')
.matches(/^[A-Za-z ]+$/, 'Numbers & Special character not allowed'),
test2: yup.number().required('Required Field').min(0).max(100).typeError('Please enter test2'),
})
.required(
)
TS2322: Type ‘NumberSchema<Maybe<number | undefined>, AnyObject, undefined, "">’ is not assignable to type ‘NumberSchema<number | undefined, AnyObject, undefined, "">’.
Type ‘Maybe<number | undefined>’ is not assignable to type ‘number | undefined’.
Type ‘null’ is not assignable to type ‘number | undefined’.
2
Answers
try this:
looks like the issue is when using the ‘when’ method as it is not compatible with the expected type
If you
console.log
test2
, you’ll see your issue – it’s an array, not a number.You also don’t need to explicitly declare the types because they are correctly inferred. Try this:
Notice
[test2]
instead oftest2
See this relevant part of the documentation: