Combining various DTOs in a seamless manner for validation in TypeScript is made easy with the class-validator fusion technique

As I delved into my NestJS project, I found the class-validation aspect to be quite bothersome. It felt like I was constantly repeating the same classes with identical decorators.

For example:

export class DTO1 {
    @IsDefined()
    @IsString()
    name: string;

    @IsDefined()
    @Type(() => Number)
    @IsInt()
    client: number;

    @IsDefined()
    @IsIn(['value1', 'value2'])
    role: 'value1' | 'value2';
}

... (other DTO classes) ...

export class Base {
    @IsDefined()
    @IsString()
    elemEveruoneHas: string;
}

export class DTO1 extends Base {
    @IsDefined()
    @IsNotEmpty()
    @Type(() => Number)
    @IsInt()
    id: number;
}

This repetition made me realize that some elements were common across multiple DTOs but not consistently enough to create a base class and extend it.

... (base class setup) ... 

I wanted to streamline this by creating generic classes for recurring elements and then generating them into specific DTOs.

The desired structure would be:

... (new DTO classes approach) ...

However, the current implementation, as shown below, is functional but lacks elegance:

... (improved but still unwieldy setup) ...

I am seeking advice on how to enhance this process so that I can avoid reconstructing the entire setup for each element class. Is there a way to incorporate a function that generates inherited classes with chaining inheritance to simplify something like DTO(Test1, Test2, Test3)?

Answer №1

Although it may not be in the precise format you had envisioned, it is possible to accomplish this using Nest's @nestjs/mapped-types and its IntersectionType. For example, you could create a DTO class like so:

export class DTO extends IntersectionType(Class1, IntersectionType(Class2, Class3)) {}
, making sure to properly nest as needed.

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

Angular 2 Directive for Ensuring Required Conditions

Is there a way to make form fields required or not based on the value of other fields? The standard RequiredValidator directive doesn't seem to support this, so I've created my own directive: @Directive({ selector: '[myRequired][ngControl ...

Exploring the compatibility of Next.js with jest for utilizing third-party ESM npm packages

Caught between the proverbial rock and a hard place. My app was built using: t3-stack: v6.2.1 - T3 stack Next.js: v12.3.1 jest: v29.3.1 Followed Next.js documentation for setting up jest with Rust Compiler at https://nextjs.org/docs/testing#setting-up-j ...

Retrieve the current state of the toggle component by extracting its value from the HTML

I have a unique component that consists of a special switch and several other elements: <mat-slide-toggle (change)="toggle($event)" [checked]="false" attX="test"> ... </mat-slide-toggle> <p> ... </p> F ...

Is it possible to retrieve a constant value while developing a customized rule in typescript-eslint?

I am currently working on implementing a custom ESLint rule using @typescript-eslint/utils that will display a warning if the prop kind of Category does not match a specific Regex pattern: import { ESLintUtils, TSESTree } from '@typescript-eslint/util ...

Is it possible to include a conditional type in TypeScript using inlining?

Apologies if this question seems basic to those well-versed in typesystems. I'm puzzled by the difference in outcomes when inlining a conditional statement in TypeScript. For instance, using the Extract conditional leads to different results dependin ...

IE11 and how it handles Typescript and promises

Currently, I am utilizing Typescript version 2.4.2 along with Webpack for compilation purposes. Despite successful compilation, when running my code on IE11, an error 'Promise' is undefined arises. Below is a glimpse of my tsconfig: { "comp ...

What impact does manually serializing gRPC request and response objects have on performance?

I am aiming to establish communication with a NodeJS microservice by sending and receiving data. The challenge lies in the fact that both my request and response objects have dynamic components - fields containing a union of 'string' and 'nu ...

When using Next.js and Jest, an error may occur stating "Element type is invalid: expected a string or a class/function but got an object."

I am currently in the process of setting up unit tests for my Next.js project. I have carefully followed the guidelines provided in the official documentation on testing. The issue I'm encountering appears to be related to either the configuration it ...

What is the best way to define a precise return type for a JSX Element?

Is it possible to define a function that returns a Button element and what would the correct return type of the function be? For example: Ex: const clickMeButton = (): Button => { return ( <Button> Click Me </Button& ...

A guide on including a class to a DOM element in Angular 6 without relying on Jquery

Currently, I have created a component template using Bootstrap that looks like this: <div class="container"> <div class="row my-4"> <div class="col-md-12 d-flex justify-content-center"> <h2> ...

Definition of Promise resolve type in Visual Code's d.ts file

Need help with: // api.js export function getLayout(){ return axios.get('/api/layout').then(res => res.data) } // api.d.ts declare interface JSONResponse { meta: object, data: Array<Field> } export declare function getLayout ...

Utilizing Type Script 1.8 with Visual Studio 2017 for older projects: A step-by-step guide

After installing Visual Studio 2017, I encountered a TypeScript error when trying to run my project. It seems that VS 2017 is using TypeScript 2.1.5, while my application was designed for TypeScript 1.8. Is there a way to make VS 17 utilize TypeScript 1.8 ...

Utilizing a library that solely enhances the functionality of the Array object

I have a library with type definitions structured like this: declare global { interface Array<T> { addRange<T>(elements: T[]): void; aggregate<U>(accumulator: (accum: U, value?: T, index?: number, list?: T[]) => an ...

A convenient utility for generating React components with pre-populated Tailwind CSS classes

When it comes to extracting local Tailwind-styled components, I tend to do it like this: const Container: React.FC = ({ children }) => ( <div className="bg-white px-5 py-5"> {children} </div> ); To simplify this process, I ...

Step-by-step guide on importing Nano (CouchDB) using Typescript

I am facing difficulty in importing and using nano in my node application. According to the documentation, the JavaScript way is: var nano = require('nano')('http://localhost:5984'); How can I achieve this with TypeScript? I attempt ...

There is no way to convert a strongly typed object into an observable object using MobX

I have been utilizing the MobX library in conjunction with ReactJS, and it has integrated quite smoothly. Currently, I am working with an observable array structured as follows: @observable items = []; When I add an object in the following manner, everyt ...

Engage with the item provided to an Angular2 component as an Input parameter

In a nutshell, the issue stems from a missing 'this' when referencing the @Input'ed variables. Currently, I have a parent class that will eventually showcase a list of "QuestionComponents". The pertinent section of the parent class templat ...

The correct way to update component state when handling an onChange event in React using Typescript

How can I update the state for 'selectedValues' in a React component called CheckboxWindow when the onChange() function is triggered by clicking on a checkbox? export const CheckboxWindow: React.FC<Props> = props => { const [selected ...

Tips for testing FormGroupDirective within a component

I am facing difficulties in testing a component with FormGroupDirective in the viewProviders section. I am unable to create a mock of the parent and set an empty formGroup. The component code is as follows: @Component({ (...) viewProviders: [ ...

What is the best way to selectively pass certain values to the args object?

Is there a way in TypeScript to pass only one argument into args and have other values be default without using "args = {}" or declaring defaults within the function to avoid issues with intellisense? function generateBrickPattern ( wallWidth: number, ...