2

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.

ViqMontana
  • 5,090
  • 3
  • 19
  • 54

2 Answers2

1

change this

class testClass
{
    public text: string;
}

to

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

You need to initialize all properties in class

Geetesh
  • 317
  • 2
  • 12
-1

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);
MattjeS
  • 1,367
  • 18
  • 35