nartc / mapper

🔥 An Object-Object AutoMapper for TypeScript 🔥
https://automapperts.netlify.app/
MIT License
985 stars 87 forks source link

AutoMap doesn't work with union types #600

Open Abd3lwahab opened 8 months ago

Abd3lwahab commented 8 months ago

This from the source code of @automapper/classes

        if (!options.type) {
            const designTypeMeta = Reflect.getMetadata(
                'design:type',
                target,
                propertyKey
            );
            // only store design:type metadata if it's not Array or Object
            if (
                designTypeMeta &&
                designTypeMeta !== Array &&
                designTypeMeta !== Object
            ) {
                options.type = () => designTypeMeta;
            }
        }

packages/classes/src/lib/automap.ts

Why this ignore the type of Object and Array?

This causing the types with union types to be ignored because the design:type metadata of them are Object

if I have this property in entity:

  @AutoMap()
  @Column('character varying', { name: 'name', nullable: true })
  name: string | null;

this will be the metadata of it "from JS build code of my app"

tslib_1.__decorate([
    (0, classes_1.AutoMap)(),
    (0, typeorm_1.Column)('character varying', { name: 'name', nullable: true }),
    tslib_1.__metadata("design:type", Object)
], Product.prototype, "name", void 0);

I tried to remove that check from @automapper/classes and that property mapped correctly with @AutoMap

I think I am missing the reason why this check added in the first place so Idk if this safe to do.

It will work fine also if I added any constructor to the @AutoMap() no matter what was the type

  @AutoMap(() => String)
  @Column('character varying', { name: 'name', nullable: true })
  name: string | null;

OR

  @AutoMap(() => Number)
  @Column('character varying', { name: 'name', nullable: true })
  name: string | null;

OR

  @AutoMap(() => Object)
  @Column('character varying', { name: 'name', nullable: true })
  name: string | null;

All this solution I tried mapped the property correctly. So idk what this constructor means to do?

I am enabling strict and strictNullChecks in tsconfig

I am willing to create any PR fix in this issue as the discussion will lead to.

Thanks.

swang2019 commented 4 months ago

I have the same question.