Typescript + NestJs + Class Transformer: How to use generic types in response DTO?

4.2k views Asked by At

I have multiple endpoints that return a response including pagination details. I would like to use one parent type for the pagination and pass in different data-types for the data param.

I tried the following, but this was not working because the statement in @Type gives the error 'T' only refers to a type, but is being used as a value here., so it expects a value/class and not 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);
  }
}

I searched and found this, which is basically working, but unfortunately it seems to transform the response twice, which causes issues with dates.

Is there any other way to do this (instead of writing multiple PaginatedResponseDto-classes?

1

There are 1 answers

3
Fortune On BEST ANSWER

You can do something along this line...

export class PaginatedResponseDto<T> {

  @Exclude()
  private type: Function;

  @Expose()
  @ApiProperty()
  @Type(opt => (opt.newObject as PaginatedResponseDto<T>).type)
  data: T[];

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