Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using classes in nestjs with strict enabled

Tags:

node.js

nestjs

I'm working with NestJS while strict is enabled in tsconfig.json.

This causes some unexpected behavior with validation. Because we are using the class-validator library for DTO validation, we have to create DTOs as classes, and because we have strict enabled, and in particular strictNullChecks:true enabled, we have to explicitly initialize every property in the class that is not optional.

If we initialize properties with default values, class-validator will fail to validate the DTO for non-existent properties because there will be default values in all properties then nestjs will call `new' on the class.

In addition, nest will call default constructor on the DTO and will not pass the received value into the constructor and so I cannot implement constructor that receives initial value.

So as far as I can see now I'll either need to disable strictNullChecks:true or find another way to validate DTO's.

Any suggestions?

like image 868
Dimkin Avatar asked Jan 16 '26 19:01

Dimkin


1 Answers

You can use the Non-null assertion operator ("!") within your DTO. You should then make shure that you use the right decorators to prevent that this property will be null or undefined. You can explicitly allow undefined if that is a valid option for a property.

export class MyDto {
    @IsString()
    readonly willNotBeUndefined!: string; // <-- notice the "!"

    @IsOptional()
    readonly couldBeUndefined?: string;

    //   Or like this: 
    //   @IsOptional()
    //   readonly couldBeUndefined: string | undefined;
}
like image 130
dude Avatar answered Jan 19 '26 11:01

dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!