[0] https://www.npmjs.com/package/class-transformer [1] https://www.npmjs.com/package/class-validator
[0] https://www.npmjs.com/package/class-transformer [1] https://www.npmjs.com/package/class-validator
Here's what it looks like to correctly annotate an array of objects with with class-validator and json-schema annotations:
@ApiProperty({ type: Foo, isArray: true })
@ValidateNested({ each: true })
@Type(() => Foo)
@IsArray()
items: Foo[];
It's not just that you have to define everything in triplicate, it's that the failure mode for forgetting any of the above is to silently not validate your data. Unless you're very careful, you don't get the safety benefits that were the whole point of using class-validator in the first place.If I were starting from scratch, I would instead consider either io-ts or a solution that involves a code generation step, where this entire category of risk is avoided.
FWIW, I'm biased against `class-transformer` because we were wondering why some of our (TypeScript-driven) API endpoints were so slow, and `classToPlain` + `plainToClass` were the culprits, comprising 2/3 of the time spent. If you look at the source code for those functions, they're kind of insane.
As mentioned in my sibling comment to yours, I do this to define DTOs that are then expressed in JSON Schema and passed through ajv, and it's pretty slick. The objects being used are all just JavaScript objects, the class is just being used as a metadata holder and something you can reference/get via `design:type`/`design:paramtype`/`design:returntype`.
EDIT: Also, as mentioned elsewhere in this thread, io-ts is a pretty good option too!
Here I have a repo benchmarking (hopefully) all of the available runtime validation packages:
https://github.com/moltar/typescript-runtime-type-benchmarks