#Is it bad practice to use the optional chaining operator in DTOs used to create documents?

3 messages · Page 1 of 1 (latest)

median warren
#

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?

ember spire
#

If the property is optional, then it should be defined with the question mark (it's not a chaining operator in this case) to provide this information to typescript.

The swagger module can infer some information from typescript, so if you do so, the ApiPropertyOptional is not necessarily needed. I am not sure if the swagger cli-plugin does this or if it's built in, but I would probably still use the ApiPropertyOptional decorator explicitly on optional properties.

median warren
#

Thanks for your clarification. 🙏