Recently I refactored some code and introduced a Map object where previously a plain object was used.
I am using Typescript so I've come to rely on the compiler shouting at me whenever I do something stupid, but in this case, my changes introduced some bugs because I was still calling Object.values(mymap)
.
It's not a Typescript issue, because this is how the Node REPL behaves:
> const somemap = new Map([['a', 1],['b', 2]])
undefined
> Object.values(somemap)
[]
> somemap.values()
[Map Iterator] { 1, 2 }
>
Why am I allowed to call Object.values()
on a Map
if the result is an empty array instead of the actual values? And if the compiler can't help us, I would think that an ESLint rule can?
This fixes it [...somemap.values()]
, but that's not the point. I would like to be protected against easy to make mistakes like this.
Why am I allowed to call
Object.values()
on aMap
if the result is an empty array instead of the actual values?
Because a map is still an object, it just doesn't have any own properties. You could in theory also create instances of a Map
subclass that has some own properties, Object.values
would then return them.
And if the compiler can't help us, I would think that an ESLint rule can?
Yes, you should be able to build a typescript-eslint rule for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With