Exposing a custom getter in a Response DTO does not work

Viewed 311

I've tried to define a custom getter like this:

import { Expose } from 'class-transformer';

export class MyDTOResponse {
  @Expose()
  id: string;

  @Expose()
  name: string;

  @Expose()
  get thisIsATest(): string {
    return 'yolo';
  }
}

This is how I transform it:

plainToClass(MyDTOResponse, MyRawDataObject, {
  excludeExtraneousValues: true,
});

As described in the documentation here: https://github.com/typestack/class-transformer#exposing-getters-and-method-return-values

However, the response is only:

{
  "id": "f8c213c7-5853-4d01-b424-cb0349a6c580",
  "name": "Clean the kitchen!"
}

I am not sure what I am doing wrong exactly, but I am missing the "thisIsATest" property.

1 Answers

plainToClass will return an instance. If you console.log this instance, you can't see the "thisIsATest" property. You can try the following code:

const res = plainToClass(MyDTOResponse, MyRawDataObject, {
  excludeExtraneousValues: true,
});

console.log(res.thisIsATest); // yolo

console.log(instanceToPlain(res))
// {
//   id: 'f8c213c7-5853-4d01-b424-cb0349a6c580',
//   name: 'Clean the kitchen!',
//   thisIsATest: 'yolo'
// }

Btw, plainToClass is deprecated, use the plainToInstance method instead.

Related