How does Yup’s casting system work?
26 October 2023 (Updated 26 October 2023)
Yup’s Schema.cast() method lets you attempt to coerce an input to match a specific schema. For example, you might use the number() type to coerce a value like "5" to 5.
Failed casts usually return null, but can also return values like NaN or unexpected strings.
// Attempts to coerce values to the correct type
const parsedUser = userSchema.cast({
name: 'jimmy',
age: '24',
createdOn: '2014-09-23T19:25:25Z',
})
// ✅ { name: 'jimmy', age: 24, createdOn: Date }
If you know that your input is already parsed, you can use { strict: true } to skip the casting:
// ❌ ValidationError "age is not a number"
const parsedUser = await userSchema.validate(
{
name: 'jimmy',
age: '24',
},
{ strict: true },
)
Tagged:
Yup
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment