typestack / class-validator

Decorator-based property validation for classes.
MIT License
10.92k stars 787 forks source link

fix: wrong property `design:type` after Typescript build #2501

Open JJBocanegra opened 3 months ago

JJBocanegra commented 3 months ago

Description

When building a file with a class with class-validator decorators, the final validation rules are defined by how the types of the property were declared in Typescript.

What was working ✅

@IsISO8601()
@IsOptional()
inspection_date?: Date | null

compiles to

__decorate([
    (0, class_validator_1.IsISO8601)(),
    (0, class_validator_1.IsOptional)(),
    __metadata("design:type", Object) // <--- Notice the `Object`
], PatchDTO.prototype, "inspection_date", void 0);

This works, an ISO string is accepted in that parameter. The important part here is that the design:type has an Object value. I will focus the code on that line from now on to avoid repetition.

What is not working ❌

Removing the null type as one of the possible types of the property.

@IsISO8601()
@IsOptional()
inspection_date?: Date

compiles to

__metadata("design:type", Date) // <--- Now it says `Date`

With this, when passing an ISO date we receive the error inspection_date must be a valid ISO 8601 date string.

I know that it shouldn't be a Date type, but why is Typescript defining how the validator should work?

Expected behavior

Typescript types influences on the validation of properties .

Actual behavior

The only influence should come from the decorators. If I have a mistake in my types I shouldn't receive an Bad Request error if the request was actually a valid one.