Using Generic Types in Response DTO with Typescript, NestJs, and Class Transformer

In my project, I am dealing with multiple endpoints that provide responses along with pagination details. My goal is to have a single parent type for the pagination and be able to use different data types for the data parameter.

I attempted the following approach, but encountered a problem where the statement within @Type resulted in an error message stating

'T' only refers to a type, but is being used as a value here.
, indicating that it requires a value or class rather than a type:

export class PaginatedResponseDto<T> {
  @Expose()
  @ApiProperty()
  skip: number;

  @Expose()
  @ApiProperty()
  take: number;

  @Expose()
  @ApiProperty()
  count: number;

  @Expose()
  @ApiProperty()
  @Type(() => T[]) // <- this is not working, because I cannot use `T` here
  data: T[];

  constructor(data: any) {
    Object.assign(this, data);
  }
}

During my research, I came across a solution (reference link provided) that seemed promising, although it led to double transformation of the response, causing complications with date values.

I am curious if there exists an alternative method to achieve this objective, instead of creating multiple PaginatedResponseDto classes?

Answer №1

If you're looking to achieve a similar outcome, consider the following approach...

export class PaginatedResponseDto<T> {

  @Exclude()
  private category: Function;

  @Expose()
  @ApiProperty()
  @Type(config => (config.newObject as PaginatedResponseDto<T>).category)
  items: T[];

  constructor(category: Function) {
    this.category = category;
  }
}

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

Using Angular to Apply a Custom Validation Condition on a FormGroup Nested Within Another FormGroup

I am facing an issue with my form validation logic. I have a set of checkboxes that need to be validated only when a specific value is selected from a dropdown. The current validator checks the checkboxes regardless of the dropdown value. Here's the c ...

Using Conditionals in React Props

In the process of developing a component that requires two props, inside and position, I've encountered an interesting dilemma. When inside is set to true, then position is limited to left or bottom. However, if inside is set to false, then position c ...

Establish a user profile and define custom claims using Firebase Authentication

When a new user is registered, certain values for user access control are set up immediately. The issue arises when the data set is only visible in the subsequent sessions after logging out of the authenticated user session that was created. My challenge ...

Callback after completion of a for loop in Angular TypeScript

During the execution of my javascript async function, I encountered a situation where my printing code was running before the div creation. I needed to ensure that my print code would run only after the completion of the for loop, but I struggled to find a ...

Learn the proper way to specify the return type of a function as a class, rather than an instance, in Typescript

Is there a way to declare that a function returns a generic class definition? I have tried the following for non-generic classes, but it does not work for generic ones: export function composeAll(composeFunction: Function, depsFunction: Function): (compon ...

"Implementing self-referencing mongoose models in Typescript: A step-by-step guide

I have a model: const message = new mongoose.Schema({ id: { type: ObjectId, required: true }, text: { type: String }, replies: [message] }); Looking to create a document structure like this: { "id": 1, "text": "Main Message", "replies": [ ...

Unraveling the Mystery of @Input and @Output Aliases in Angular 2

After researching about the @Input() and @Output() decorators, I discovered that we have the option to use an alias instead of the property name for these decorators. For example: class ProductImage { //Aliased @Input('myProduct') pro ...

Unleashing the potential of an endless animation by incorporating pauses between each iteration

I am trying to create an infinite animation using animate css but I want to add a delay between each iteration. After exploring various options, I first attempted to achieve this using plain JavaScript. Here is the HTML snippet: <div id="item" class= ...

In Typescript, type errors in Object Spread Syntax are not causing any issues

In the following code snippets, the object spread syntax should generate a typescript error, but surprisingly no errors are being thrown. It's important to note that I intentionally added a typo in the address property for this test. Snippet A.1. - n ...

What kind of null/undefined is being assumed?

system details: Visual Studio Code Version: 1.47.3 Typescript Version: 4.0.0-dev.20200727 tsconfig.js: "strict": true, code example: let x = null; // x is any type let y = x; // x is null type(why? x is any type on top), y is null type x = 1; / ...

Is it possible to synchronize the Lit cached DOM with the live DOM?

Utilizing the Lit framework for constructing my front-end UI components has been a game-changer. However, I have encountered an issue while incorporating our internal company design system's web components. One of these components has the ability to r ...

Discover the data type without using the extends keyword within an interface in Typescript

I'm struggling with making my code declarative enough. I want to infer a type inside an interface scope and then use that same type as an argument for a method within the interface. Here is a simple example: interface Prop { x: infer U, // ^^ ...

Displaying a div component in React and Typescript upon clicking an element

I've been working on a to-do list project using React and TypeScript. In order to display my completed tasks, I have added a "done" button to the DOM that triggers a function when clicked. Initially, I attempted to use a useState hook in the function ...

Avoiding repetitive logic in both parent and child components in Angular 8

In my parent controller, I have common requests and I also read router params for those requests. However, for the child components, I have different requests but still need to extract the same parameters from the router - resulting in duplicate code. For ...

The Angular performance may be impacted by the constant recalculation of ngStyle when clicking on various input fields

I am facing a frustrating performance issue. Within my component, I have implemented ngStyle and I would rather not rewrite it. However, every time I interact with random input fields on the same page (even from another component), the ngStyle recalculate ...

Dynamic table row that expands to show additional rows sourced from various data sets

Is there a way to expand the table row in an angular-material table when it is clicked, showing multiple sets of rows in the same column as the table? The new rows should share the same column header but not necessarily come from the same data source. Whe ...

Closing a tab in another part of the session using Typescript and Angular

Looking for a solution on how to close a tab within an Angular session that was opened from somewhere else in the same session. For instance: In Component A this.window = this.windowToken.open('Some URL', 'Some Tab Name', 'Some ...

The CSS styles are functioning correctly in index.html, but they are not applying properly in the component.html

When the UI Element is clicked, it should add the class "open" to the list item (li), causing it to open in a collapsed state. However, this functionality does not seem to be working in the xxx.component.html file. Screenshot [] ...

Exploring Angular's filtering capabilities and the ngModelChange binding

Currently, I am in the process of working on a project for a hotel. Specifically, I have been focusing on developing a reservation screen where users can input information such as the hotel name, region name, check-in and check-out dates, along with the nu ...

Issue: Module not found; Typescript error encountered in a react application

I have a load_routes.js file in the node_express folder that is responsible for loading all the routes for my project. Everything was working smoothly until I decided to change the file extension from .js to .ts. Suddenly, I started encountering the follow ...