How to tell if an object is a typed array?

Viewed 142

Right now, I achieve it by

if (obj instanceof Uint8Array || obj instanceof Uint16Array || obj instanceof Uint32Array ......

Its a very long line. I know that testing instanceof against the parent class of an object yields true so is there a parent class among those typed arrays? I tried TypedArray but according to chrome it doesn't exist.

Anyone know if there is a base class between the typed arrays? Or some other method?

3 Answers

The TypedArray prototype does exist but is not exposed directly. You can get it using Object.getPrototypeOf from any of its typed arry subclasses, like this:

>> const TypedArray = Object.getPrototypeOf(Uint8Array)
>> console.log((new Uint32Array()) instanceof TypedArray)
true

So with the above const TypedArray in scope, your check simply becomes:

if (obj instanceof TypedArray) { ... }

I know this is not a very good solution but I think you can achieve the same kind of behavior using a hacky way. Actually, I don't like this kind of solution. I used Uint8Array.__proto__, I have no idea why the prototype of Uint arrays doesn't exist in chrome.

const uint8Array = new Uint8Array();
const uint16Array = new Uint16Array();
const uint32Array = new Uint32Array();

console.log(uint8Array instanceof Uint8Array.__proto__); //true
console.log(uint16Array instanceof Uint8Array.__proto__); //true
console.log(uint32Array instanceof Uint8Array.__proto__); //true

Edit:

const typedArrays = [new Uint8Array(), new Uint16Array(), new Uint32Array()];

const result = typedArrays.every(elem => elem instanceof Uint8Array.__proto__);

console.log(result);

So, you can check any typed array using Uint8Array.__proto__.

Edit 2:

const isTypedArray = (arg) => {
  return arg instanceof Uint8Array.__proto__;
};


console.log(isTypedArray(uint8Array));// true
console.log(isTypedArray(uint16Array));// true
console.log(isTypedArray(uint32Array));// true

How about shorten it by checking if it not a normal array like this :

if (!(obj instanceof Array)) {
  // Do stuff with typed array
}
Related