I have a class which contains a Map as an attribute:
export class Test {
@Type(() => Number)
public testMap: Map<string, number>;
constructor() {
this.testMap = new Map();
}
}
My map contains a key-value pair, e.g. "size" -> 1337 which is preserved when calling instanceToPlain but is lost when calling plainToInstance
Minimal code-snippet showcasing the problem
The following code adds some values to the map, converts it to plain and then back to the instance of Test.
Description
I have a class which contains a Map as an attribute:
My map contains a key-value pair, e.g.
"size" -> 1337
which is preserved when callinginstanceToPlain
but is lost when callingplainToInstance
Minimal code-snippet showcasing the problem The following code adds some values to the map, converts it to plain and then back to the instance of Test.
And my tsconfig.json
Expected behavior
I expect the map containing exactly the same (key, value) pairs in the
test
and thetest2
instance.Actual behavior
The map in
test2
is missing thesize
value. Here is the console output of the code above:The same happens for other keys which are part of the Map prototype itself, like
has
,clear
, ...Further analysis
I already inspected the code and found the problem, which is in this part of the code: https://github.com/typestack/class-transformer/blob/67fec03b9e32b5d020a4ee9e8ebff35e5dbfb2d7/src/TransformOperationExecutor.ts#L298-L306 When this code is called during transformation
newValueKey
issize
anddescriptor
then is{get: [Function: get size],set: undefined,enumerable: false,configurable: true}
which makes the expression in L303 evaluate to true and thus skips addingsize
to the map with thecontinue
in L306.While skipping these values for objects makes a lot of sense it does not for the
Map
type: https://github.com/typestack/class-transformer/blob/67fec03b9e32b5d020a4ee9e8ebff35e5dbfb2d7/src/TransformOperationExecutor.ts#L344-L350 In this code snippet when the value is actually added to the object or map there is a check if the type is aMap
and if yes, the.set()
function ofMap
is used, thus not inducing any problems with keys likesize
Possible fix
A possible fix should be pretty easy, just replace this code https://github.com/typestack/class-transformer/blob/67fec03b9e32b5d020a4ee9e8ebff35e5dbfb2d7/src/TransformOperationExecutor.ts#L297 by