Force typescript undefined property declaration

70 views Asked by At

I have a monorepo setup with multiple frontends and a backend, all written in typescript. There is a shared package types that defines the request and response dtos. Here is sample

Inside types

export interface CreateBookRequest {
    title: string;
    year?: number
}

I can easily import this in my frontends and make sure the request is always the same.

In backend I have nestjs with class validator to check my dto so i need to do

export class CreateBookRequestDto implements CreateBookRequest {
    @IsString()
    @IsOptional()
    readonly title: string;

    @IsNumber()
    @IsOptional()
    readonly year?: number;
}

This works fine, I'm happy with the result

But suppose i want to add an optional property to CreateBookRequest like

export interface CreateBookRequest {
    title: string;
    year?: number;
    author?: string;
}

In this case, typescript is not indicating me in any way on CreateBookRequestDto that there is a new property added, because it's optional. This causes problems because even if the property is optional, I still need to add it to my DTO in order for it to be validated with the proper decorators. With my configuration, non-validated properties will be stripped from the request.

Is there a way to make typescript (or event eslint) yell at me for this, or a solution on the class-validator side?

0

There are 0 answers