typescriptdtoclass-transformer

Get property from nested object


I have this DTO:

import { Expose, Type } from 'class-transformer';
import { UserDto } from '../../../admin/users/dtos/user.dto';

export class CompanyDto {
  constructor(partial: Partial<CompanyDto>) {
    Object.assign(this, partial);
  }

  @Expose()
  id!: number;

  @Expose()
  companyName!: string;

  @Expose()
  companyCode!: string;

  @Expose()
  country!: string;

  @Expose()
  headQuarter!: string;

  @Expose()
  @Type(() => UserDto)
  user!: UserDto;

  @Expose()
  createdBy!: string;

  @Expose()
  createdAt!: Date;
}

This is the object from the DB:

id: 12,
companyName: 'some company',
companyCode: '0001',
country: 'germany',
headQuarter: 'berlin',
createdAt: 2025-04-26T11:31:57.891Z,
user: User { userName: 'a12' }

I convert this into the DTO:

  plainToInstance(CompanyDto, new CompanyDto(company), {
    excludeExtraneousValues: true,
  }),

And I get a JSON like this:

"id": 12,
"companyName": "some company",
"companyCode": "0001",
"country": "germany",
"headQuarter": "berlin",
"user": {
    "userName": "a12"
},
"createdAt": "2025-04-26T11:31:57.891Z"

Instead of the user object, I only need a new property createdBy, which has the value of userName. I tried with getter, I tried with transform, no success. How can I get the content of the userName in the field createdBy?

There is no debug details, no errors, etc. I simply don't get in the JSON the createdBy field with its data.


Solution

  • This did the trick:

     @Expose()
      @Transform(({ obj }) => obj.user.userName)
      createdBy!: string;