mobxjs / serializr

Serialize and deserialize complex object graphs to and from JSON and Javascript classes
MIT License
766 stars 52 forks source link

how do I keep the map key as number #161

Closed jianyunli closed 1 year ago

jianyunli commented 2 years ago

I used map() for my ES6 Map myField, looks like it converted key to strings, how can I keep it as the number?

createModelSchema(MyClass, { myField: map() })

Lechros commented 2 years ago

I extended custom with list to support dictionary primitive key/any PropSchema values. Map<K, V> =serializer=> [K, V][] =deserializer=> Map<K, V>

NaridaL commented 1 year ago

Was the actual key being converted to string, or were the types wrong?

Lechros commented 1 year ago

It is converted to JS object, which only supports string key.

NaridaL commented 1 year ago

Right.. map converts to a JSON object which has string keys. You can use afterDeserialize to fix this if it simple but the recommended approach is to use mapAsArray which is made for this case explictly:

https://github.com/mobxjs/serializr/blob/master/src/types/mapAsArray.ts

For ES6 maps this has the benefit of being allowed to have non-string keys in the map.