AutoMapper-ts mapped object is empty when I try to convert it to a type in TypeScript

2.1k Views Asked by At

I have the following class:

class testClass
{
    public text: string;
}

I create the following map using AutoMapper-ts:

AutoMapper.createMap('source', 'dest')
            .convertToType(testClass);

And then do my mapping:

this.newObject = AutoMapper.map('source', 'dest', this.anotherObjectWithSameProperties);

But this.newObject is always an empty testClass object. If I remove the following line:

.convertToType(testClass);

Then the properties will be mapped to this.newObject as expected, but the type of this.newObject will be Object instead of testClass.

How can I map an object to another object using automapper-ts, but have the new object as the required type?

UPDATE

The AutoMapper-TS documentation show cases this method with a unit test but this unit test specifies the mapping explicitly:

.forMember('property', (opts: AutoMapperJs.IMemberConfigurationOptions) => { opts.mapFrom('ApiProperty'); })

If I do this with my text property like so:

AutoMapper.createMap('source', 'dest')
    .forMember('text', 'text');
    .convertToType(testClass);

then my implementation works as expected, but that defies the whole point of using automapper in the first place.

2

There are 2 best solutions below

1
On

you cast to the specified type after the map like so:

this.newObject = AutoMapper.map('source', 'dest', this.anotherObjectWithSameProperties) as testClass;

or

this.newObject = <testClass> AutoMapper.map('source', 'dest', this.anotherObjectWithSameProperties);
1
On

change this

class testClass
{
    public text: string;
}

to

class testClass
{
    public text: string='';
}

You need to initialize all properties in class