Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent the mistake of calling Object.values() on a Map

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.

like image 575
Thijs Koerselman Avatar asked Sep 12 '25 07:09

Thijs Koerselman


1 Answers

Why am I allowed to call Object.values() on a Map 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.

like image 142
Bergi Avatar answered Sep 13 '25 22:09

Bergi