Johar Zaman
Johar Zaman

Reputation: 2123

How to check the type of es6 proxy in Javascript?

I am working with ES6 Proxy. I have created a proxy of an array, now when i check the type of proxy it is giving me as Object type.

Question:

How can i check if the proxy i have created was for array or object?

Example:

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

const arrProxy = new Proxy(arr, {});

alert(typeof(arrProxy));

UPDATE (SOLUTION): Instead of using typeof, we should use Array.isArray

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

const arrProxy = new Proxy(arr, {});

alert(Array.isArray(arrProxy));

Upvotes: 6

Views: 5200

Answers (3)

marsibarsi
marsibarsi

Reputation: 1073

There is also one way to do this using instanceof:

if (arrProxy instanceof Array) {
   console.log('This is an array!');
}

Upvotes: 1

Lydia Yuan
Lydia Yuan

Reputation: 39

As other answers suggest, you cannot tell if something is a proxy.

So you might need to implement it yourself.

Here is an example from: https://exploringjs.com/deep-js/ch_proxies.html#transparent-virtualization-and-handler-encapsulation

const proxies = new WeakSet();

export function createProxy(obj) {
  const handler = {};
  const proxy = new Proxy(obj, handler);
  proxies.add(proxy);
  return proxy;
}

export function isProxy(obj) {
  return proxies.has(obj);
}

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1075925

You can't tell that a proxy is a proxy. That's part of the point of them, they provide a facade (one you can't detect) around another object.

As far as code looking at your arrProxy can tell, it's an array:

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

const arrProxy = new Proxy(arr, {});

console.log(Array.isArray(arrProxy)); // true

Separately: typeof is very general, it gives you "object" for a huge range of things: Anything that's of an object (not primitive) type (including null). So typeof new Map(), typeof new Set(), typeof null, typeof document (on browsers), etc., will all give you "object". (Also note that typeof is an operator, not a function; no need for the () in your code sample.)

Upvotes: 6

Related Questions