Avoiding the presence of null values in NestJs dto properties

Is there a way to ensure that nestjs dto optional properties do not have null values?

@ApiProperty({
  type: String,
  format: 'string',
})
@IsOptional()
@IsString()
readonly name?: string;

One potential solution is:

@ApiProperty({
  type: String,
  format: 'string',
  required: false, // This will make it optional for the docs
})
@ValidateIf((o) => o.name !== undefined) 
@IsString()
readonly name?: string;

I wish there was something like: @IsNotNull

Answer №1

During our discussion, it became evident that having a clear and simple decorator is important. However, the current behavior of class-validator's @IsOptional poses challenges when used in conjunction with other decorators like @NotEquals(null), as it forces validation to be ignored if the value is null or undefined.

@IsOptional() verifies if the value is empty (=== null, === undefined) and disregards all property validators.

Unfortunately, there hasn't been any progress from the library maintainers to address this issue yet. You can reference these open problems:

The decision is now in your hands - you have the option to create your own decorator for your DTO class or explore alternatives like class-validator-extended. This package offers an @Optional decorator (they recommend importing from

class-validator-extended/dist/minimal
if you don't use dayjs).

If installing the entire npm package just for one decorator seems excessive, you can take inspiration from this snippet in class-validator-extended/optional.decorator.ts#L21

Answer №2

If you want to ensure that the key value is not null and use optional at the same time, 'transform' may be a suitable choice in this scenario. By using 'transform', you can avoid skipping this important check, which helps prevent errors when checking for 'isEnum' and returning false.

For instance:

 @IsOptional()
  @IsEnum(UserType)
  @Transform(({ value }) => {
    if (value === null || value === undefined) {
      return false;
    } else {
      return value;
    }
  })
  type?: UserType;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps can I take to troubleshoot and fix the issue of a Duplicate identifier 'DateType' error during the React/Typescript building process

Utilizing the MUI library, I have also installed the @mui/x-date-pickers library. In order for my datepicker component to function properly, I need to install the @date-io/date-fns/ library as well. However, upon running yarn build, I encountered the fol ...

Each time a tab is visited, the viewDidLoad function is only triggered once for its events subscription

Here's the code snippet I'm working with: import { Component, ViewChild } from '@angular/core'; import { IonicPage, NavController, Nav, App, Tabs} from 'ionic-angular'; @Component({ templateUrl: 'tabs.html' }) e ...

Ensuring Consistency in Array Lengths of Two Props in a Functional Component using TypeScript

Is there a way to ensure that two separate arrays passed as props to a functional component in React have the same length using TypeScript, triggering an error if they do not match? For instance, when utilizing this component within other components, it sh ...

What steps can be taken to fix error TS2731 within this code snippet?

I've been working through a book and encountered an issue with the code below. // This code defines a function called printProperty that has two generic type parameters function printProperty<T, K extends keyof T> (object: T, key: K) { let pro ...

Leveraging Nextjs Link alongside MUI Link or MUI Button within a different functional component (varieties)

Currently in my development setup, I am utilizing Next.js (10.2) and Material-UI (MUI) with Typescript. In the process, I have implemented a custom Link component: Link.tsx (/components) [...] On top of that, I have created another iteration which functi ...

Transforming an array of flat data into a hierarchical tree structure

I'm facing a challenge with my script. I have an Array of FlatObj and some rules, and I need to create a converter function that transforms them into TreeObj. The Rules are: If an object has a higher depth, it should be a child of an object with a l ...

Use various onChange functions for sliding toggle

I need assistance with a toggle app I'm developing that includes two slide toggles. Even though I have separate onChange() methods for each toggle, toggling one slide-toggle also changes the value of the other slide toggle. The toggle state is saved i ...

Injecting live data into an input field within a table using Angular 4

Trying to create a dynamic row table with input fields in all cells. The loaded data is static, and I'm facing issues adding more data in the view. However, the functionality to add and delete rows is working fine. I have experimented with ngModel and ...

Using TypeScript, extract the value of a Promise from a Page Object

Struggling to retrieve a value from a WebDriver promise in a Protractor solution using TypeScript, the response keeps coming back as undefined. get nameInput(): string { var value: string; this.nameElement.getAttribute('value').then(v =& ...

Error in BehaviorSubject<any[]>: Unable to assign type 'any[] | null' to type 'any[]'

When I try to pass a BehaviorSubject from my CacheService to a component @Input() that expects an array, I encounter an error stating that 'any[] | Type 'any[] | null' is not assignable to type 'any[]'. This occurs even though the ...

Is there a way to verify the functionality of this Angular 2 service?

In my Angular application, there is a service called BookService: import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; @Injectable() export class BookService { constructor(private http: Http) {} getL ...

What is the process for deconstructing errors from the RTK Query Mutation Hook?

Currently, I am utilizing redux toolkit query for handling my data fetching API. One issue that I have encountered is with error handling. When an error is returned from the server, it comes in as an object with nested data. However, when trying to access ...

Is there a way to signal an error within an Observable function that can handle multiple scenarios depending on the specific page being viewed in an Angular application?

Currently, I have a function called getElementList() which returns Observable<Element[]>. The goal is to handle different scenarios based on the user's current page - two cases for two specific pages and one error case. However, I am struggling ...

The challenge of handling Set type in TypeScript errors

I'm currently facing two errors while trying to convert a function to TypeScript. The issue lies with the parameters, which are of type Set import type {Set} from 'typescript' function union<T>(setA: Set<T>, setB: Set<T>) ...

Function arity-based type guard

Consider a scenario where there is a function with multiple optional parameters. Why does the function's arity not have a type guard based on the arguments keyword and what are some solutions that do not require altering the implementation or resorti ...

Upon logging in, the Angular page fails to update with the latest information

Working on my initial login implementation in Angular. Everything seems to be functioning correctly - the user can log in, gets redirected to the GiveDashboardComponent, and the "login" button on the nav bar changes to "logout" accordingly. However, I noti ...

What's the best way to display NestJS errors in my front-end component?

I have a working NestJS application where I handle errors by throwing a BadRequestException when necessary: // my-service.ts try { return await signUp(...); } catch (err) { throw new BadRequestException({ description: err.message, }); ...

Unspecified Angular Component @Input Reported as Missing

My component is set up to accept an @Input in this way: @Input() item:Item; // causing error! The input value is passed to the component like so: <my-component [item]="thatItem"></my-component> When using strict mode, I am encounter ...

Adjusting the Port Setting in Nuxt 3

After trying the old solution without success, I decided to refer to the Nuxt 3 documentation for answers, only to find that it was not up to date. So, is there a way to change the Nuxt 3 port without modifying the dev script, similar to what @kissu did h ...

What is the method for running a powershell script within protractor testing?

I am attempting to run a powershell script within my protractor test. Protractor spec.ts it("Executing Powershell Script", async () => { browser.get('http://mywebsite.com') var spawn = require('child_process').spawn; ...