#What is the point of `expectedType` in the `ValidationPipe` options?

1 messages · Page 1 of 1 (latest)

buoyant crescent
#

There is an option for expectedType when creating the ValidationPipe. I can't find anything about it in the docs, and everything seems to work fine without it (I've tested class-validator/transformer, using the pipe with generics, multiple parameters, nested objects). What is this option for?

graceful kernel
#

you use that when you can't rely on typescript reflection to define the type

#

like this:

#

seince opts has an union type, and since TSC will erase those types, ValidationPipe cannot infer the expected class to use when validating opts

buoyant crescent
#

Oh interesting, so its for unions specifically?
What you're showing is a parameter with three different structures based on the same dto, and then passing the dto as the expectedType. If that dto has @IsDefined on customerId, and the actual opts being passed in is of the first variant (withoutcustomerId), wouldn't the validation fail?
Either way, it would be good to add this to the docs about the built-in validation pipe somewhere

graceful kernel
#

it's for anything that prevents from having values as a type

#

opts: FooDTO
if DTO is a class, then it's being used as a value here. So ValidationPipe can infer the expected type

#

for any other scenario, you must explicit tell the expected type
It's a limitation on how TS reflection works, you know

#

just click here in the docs page that you want to edit to improve it 🙂 the docs are mainly written by the community

buoyant crescent
#

Will do, thank you. Have a good day!