Francisco Presencia Francisco Presencia - 16 days ago 5x
Javascript Question

Proxy index gets converted to string

Trying out the new Proxy objects, I am surprised that when a proxy is set the key is automatically converted to a string:

var arr = ['a', 'b', 'c'];

arr = new Proxy(arr, {
get: (original, key) => {
alert(typeof key);
return original[key];

arr[1]; // expected an alert with 'number'; got 'string' instead

There I would expect that
typeof key
would be
, since I am passing it a number. However, it gets converted to a string inside
somehow and the actual alerted type is
. You can see a small JSFiddle here that showcases the problem.
is still an Array even after passing it through the proxy.

So, how could I differentiate from passing a string and a number? I could just regex it out as in
, however it'd not differentiate between these situations and it just feels like a hack:



Property keys can be only strings or symbols. If you're using something different, like a number, it always gets converted to a string first. Therefore, when using a Proxy you can't distinguish between these two operations:


Both of them will trigger the Proxy get handler with '1' as the property key.

Also, the fact that you're using an array doesn't change anything―it works the same with arrays (which are special kind of objects) as it works with plain objects.

See also The Object Type in the specification.