Specificity of schema validation errors is lost if a type is a union type
Prerequisites
- [X] I have written a descriptive issue title
- [X] I have searched existing issues to ensure the bug has not already been reported
Fastify version
4.27
Plugin version
No response
Node.js version
20
Operating system
macOS
Operating system version (i.e. 20.04, 11.3, 10)
14.6
Description
When serializing nested objects using a Typebox schema, the validation errors returned from fast-json-stringify are different depending on whether or not the type is a union type.
Take the MRE below. Hitting the endpoint results in a validation error, and with the code below I get the message The value of '#/properties/foo' does not match schema definition. But if I comment out the Type.Null() in the union, then I get a different error message of "\"bar\" is required!. I think the latter is more useful, but honestly a combination of the two might be the most useful because then you know which object failed validation and which field it failed on.
MRE below:
const app = Fastify().withTypeProvider<TypeBoxTypeProvider>();
const schema = Type.Object({
foo: Type.Union([
Type.Null(),
Type.Object({
bar: Type.String(),
}),
]),
});
app.route({
method: 'GET',
path: '/',
schema: {
response: {
'2xx': schema,
},
},
handler: async (req, reply) => {
return { foo: {} };
},
});
Link to code that reproduces the bug
No response
Expected Behavior
I would expect/hope for a more helpful message in the former case, because in my application I have a bunch of nullable nested fields that I was getting confusing error messages for. Once I made them not nullable (by removing Type.Null() from the union), I started to see which fields were actually causing the errors.