Utilizing generics with Swagger in NestJS

export class PaginatedResult<T> {

 @Expose()
 @ApiResponseProperty(type: T}) // It's unfortunate that this isn't working because it's a type but being used as a value
 @Transform(({ obj }) =>
  obj.data.map((data) => new obj.classConstructor(data)),
 )
 data: T[];
}

The data is of Type T, which includes options such as Item or Tag and more. However, Swagger only displays Item even on endpoints where the ResponseType is defined as:

{type: PaginatedResult<Tag>}

Is there any workaround for this issue?

Answer №1

Instead of referencing the Property directly, I came up with a solution that involves creating a custom ApiResponseDecorator. This decorator takes the generic type as input and populates a schema with it:

This implementation is specifically for NestJs.

export const CustomApiResponse = <GenericType extends Type<unknown>>(data: GenericType ) =>
  applyDecorators(
    ApiExtraModels(ModelWithGeneric, data),
    ApiOkResponse({
      description: `The paginated result of ${data.name}`,
      schema: {
        allOf: [
          { $ref: getSchemaPath(ModelWithGeneric) },
          {
            properties: {
              genericFieldName: {
                type: 'array',
                items: { $ref: getSchemaPath(data) },
              },},},],},}))

You can use it like this:

@Controller('')
export class SomeController {

  @Get('/')
  CustomApiResponse(GenericType)
  async get(): Promise<ModelWithGeneric<GenericType>> {}
}

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

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 ...

Encountering difficulties when attempting to upload a file to Google Cloud Platform using Multer in a Node.js

I am currently experimenting with uploading a single file using Multer and the "multipart/form-data" content type to a Google Cloud Storage bucket. For this task, I am utilizing "Multer.memoryStorage()" and "@google-cloud/storage" try { const docume ...

Setting up TypeScript in Node.js

A snippet of the error encountered in the node.js command prompt is as follows: C:\Windows\System32>npm i -g typescript npm ERR! code UNABLE_TO_VERIFY_LEAF_SIGNATURE npm ERR! errno UNABLE_TO_VERIFY_LEAF_SIGNATURE npm ERR! request to https:/ ...

My Nextjs project is encountering deployment issues with both Netlify and Heroku

Whenever I attempt to deploy my application on Heroku or Netlify, I encounter an ERROR related to an incorrect import path. It's perplexing because the import is accurate and functions properly locally. Log ./pages/_app.tsx:7:27 6:31:19 PM: Type err ...

Steps for confirming a property setting on an interface

I am working with the following interface export interface Command { id: CommandId; disabled: boolean; } My goal is to verify that the 'disabled' property has been changed. Here are my attempts: 1) Creating an object and checking if t ...

The parameter type (key: string, id: string, pagination: number) in the argument does not match the expected type of Boolean for the parameter

I'm facing an issue while trying to implement the following documentation: https://swr.vercel.app/ using my own setup: import React, { useEffect } from 'react' import PatientsTable from 'components/patients/PatientsTable' import ...

When using Typescript, I am encountering an issue where declared modules in my declaration file, specifically those with the file

One of the declarations in my ./src/types.d.ts file includes various modules: /// <reference types="@emotion/react/types/css-prop" /> import '@emotion/react'; import { PureComponent, SVGProps } from 'react'; declare mod ...

Creating a .d.ts file for a JavaScript file that exports a plain object - tips and best practices

I am attempting to include a .d.ts file for an existing js file. The type.js file looks like this: // type.js export default { NORMAL: '001', CHECK: '002', }; Now, I have added a type.d.ts file as follows: // type.d.ts decla ...

Errors in the @babel/types during the ng build process in Angular version 8.2.14

When I execute the command 'ng build' for my Angular App, I encounter the following errors: ERROR in ../node_modules/@types/babel-types/index.d.ts:1769:96 - error TS1144: '{' or ';' expected. 1769 export function assertArrayE ...

Retrieve all elements within an Angular6 Directive that share the same name as the Directive

I have created a custom Directive called isSelected and applied it to several elements in different components as shown below: <i isSelected class="icon"></i> <i isSelected class="icon"></i> <i isSelected class="icon"></i ...

Angular2 Error: Cannot have two identifiers with the same name, 'PropertyKey' is duplicated

I am currently developing an application with angular2 using angular-cli. Unfortunately, angular-in-memory-web-api was not included by default. After some research, I manually added the line "angular-in-memory-web-api": "~0.1.5" to my ...

What causes the error message "No exported member 'ɵɵFactoryDeclaration' in @angular/core/core" to appear during project compilation?

I am facing an issue where the global Angular CLI version is 13.0.1 and the local version in my project is 10.2.3. Despite making changes to some components (without touching package.json), I encountered an error during the build step of my bitbucket pipel ...

Is importing all models into every component considered poor practice?

At my workplace, there is a practice in the legacy code where every single model is imported into all components, regardless of whether they are needed or not. For example: import * as models from '../../view-models/models' ....... let parrot: m ...

Using Typescript types or a linter can help avoid mistakenly rendering the raw function in JSX instead of its executed return value

Seeking a resolution to prevent the recurring mistake I often make, as shown below: export function scratch_1 (props: scratch_1Props): ReactElement | null { function renderA (): string { return "A"; } function renderB (): string { ...

Pattern Matching for Excluding Multiple Specific Phrases

I need to restrict what a user can enter into a field based on previous entries that are already in the system. For instance, the user has already entered these values into the database: ["typescript", "C#", "python"] If they type one of these existing ...

Here's how you can transfer the AceEditor value to the component state in ReactJS by utilizing the onClick event of a button

I'm facing a challenge implementing a customized CodeMirror using ACE Editor. I've experimented with incorporating state alongside the 'onClick' button parameter, but I haven't been successful in making it functional. import Rea ...

When using videojs, I have the ability to include a Text Track event handler, however, there is currently no option to remove it

I implemented a listener for the 'cuechange' event on a Text Track and it's functioning correctly. However, I am unable to figure out how to remove this listener. I have attempted the instructions below to remove the listener, but it continu ...

Error message while attempting to update devextreme-datagrid: "Received HTTP failure response for an unknown URL: 0 Unknown Error"

Need help with updating the devextreme-datagrid. Can anyone assist? lineController.js router.put("/:id", (req, res) => { if (!ObjectId.isValid(req.params.id)) return res.status(400).send(`No record with given id : ${req.params.id}`); ...

Utilizing the NPM package as a JSX Component is prohibited due to type errors

I've been encountering some unusual type errors in my TypeScript project with certain packages. For example: 'TimeAgo' cannot be used as a JSX component. Its instance type 'ReactTimeago<keyof IntrinsicElements | ComponentType<{} ...

strictNullChecks and the dissemination of null values

Considering implementing the strictNullChecks flag in a large code base presents some challenges. While it is undeniably a valuable tool, the abundance of null types in interface definitions may be impacting the code's readability. This is particularl ...