For example, I've got this DTO:
import { IsNotEmpty, IsString, IsOptional } from 'class-validator';
import { ApiPropertyOptional } from '@nestjs/swagger';
export class CreateCategoryDto {
@IsNotEmpty()
@IsString()
readonly title: string;
@IsOptional()
@ApiPropertyOptional()
@IsString()
readonly description: string;
}
Notice the @ApiPropertyOptional() decorator in the description property. Without this, the property will be flagged as required when I visit the swagger docs endpoint.
However, I noticed that instead of using the @ApiPropertyOptional() decorator, I could simply mark the description property with the optional chaining operator like this:
@IsOptional()
@IsString()
readonly description?: string;
Now, in my swagger docs the description property will be correctly flagged as an optional property.
Not sure if this sounds dumb; the reason I'm asking this is because I cannot recall seeing any tutorials or guides supporting that (instead, they always use the @ApiPropertyOptional() decorator, and no properties are marked with the optional chaning op) and I'm honestly curious.
Is it considered bad practice to use the optional chaining operator in DTOs like this example? In fact, isn't it even better taking into consideration that you can actually see in your IDE's auto complete that a property is optional?