class-transformer icon indicating copy to clipboard operation
class-transformer copied to clipboard

fix: `@Expose` with same name not evaluated for all properties

Open JeffreyArt1 opened this issue 1 year ago • 1 comments

Description

I have noticed that when using the @Expose decorator with the same name for multiple properties in the same class, the transform function is only evaluated for the first property.

For example, consider the following code:

const plain = {
  name: {
    first: 'John',
    last: 'Doe',
  },
};

@Exclude()
class Person {
  @Expose({ name: 'name' })
  @Transform(({ value }) => value.first)
  firstName: string;

  @Expose({ name: 'name' })
  @Transform(({ value }) => value.last)
  lastName: string;
}

Here's a snippet

Expected behavior

console.log(plainToClass(Person, plain)); // Person { firstName: "John", lastName: "Doe" }

Actual behavior

console.log(plainToClass(Person, plain)); // Person { firstName: "John" }

When plainToClass is called with this class and a plain object, only the transform function for the firstName property is evaluated, while the lastName property remains undefined.

I believe this is a bug in the class-transformer library, as both properties should be transformed based on their respective transform functions. Correct me if i'm wrong.

JeffreyArt1 avatar Apr 12 '23 16:04 JeffreyArt1

@JeffreyArt1 I have the same issue, my workaround is

const plain = {
  name: {
    first: 'John',
    last: 'Doe',
  },
};

@Exclude()
class Person {
  @Expose()
  @Transform(({ obj }) => obj.name.first)
  firstName: string;

  @Expose()
  @Transform(({ obj }) => obj.name.last)
  lastName: string;
}

amrsalama avatar Nov 06 '23 11:11 amrsalama