Typed Array Kind Detector
The `which-typed-array` package provides a robust and cross-realm method for determining the specific kind of JavaScript Typed Array a given value is. Unlike `instanceof`, it works reliably across different JavaScript realms (e.g., iframes, web workers) and bypasses issues with `Symbol.toStringTag` being overridden. It returns the string name of the Typed Array (e.g., 'Int8Array', 'Uint32Array', 'Float64Array') or `false` if the value is not a Typed Array. The current stable version is 1.1.20, indicating a mature and well-tested utility. Given its focused scope and the stability of the underlying JavaScript `TypedArray` specification, new releases are generally infrequent, focusing on compatibility and minor improvements. It's a foundational utility often used by libraries that need to handle various JavaScript value types precisely.
Common errors
-
TypeError: whichTypedArray is not a function
cause Attempting to use `whichTypedArray` after an incorrect import, specifically `import { whichTypedArray } from 'which-typed-array';`fixChange your import statement to `import whichTypedArray from 'which-typed-array';` for ES Modules or `const whichTypedArray = require('which-typed-array');` for CommonJS. -
ReferenceError: BigInt64Array is not defined
cause Attempting to create or check `BigInt64Array` or `BigUint64Array` in an environment that does not support BigInt Typed Arrays (e.g., older Node.js versions or browsers).fixEnsure your JavaScript environment supports BigInt Typed Arrays. If targeting older environments, wrap usage in a check: `if (typeof BigInt64Array !== 'undefined') { /* use BigInt64Array */ }`.
Warnings
- gotcha This package is designed specifically for standard JavaScript Typed Arrays (e.g., Int8Array, Float64Array). It will return `false` for ArrayBuffer, DataView, or any custom objects that might mimic Typed Array behavior but are not true `TypedArray` instances.
- gotcha The primary function is a default export, meaning it should be imported directly as `import whichTypedArray from 'which-typed-array'` in ESM. Using a named import or destructuring will result in `undefined`.
Install
-
npm install which-typed-array -
yarn add which-typed-array -
pnpm add which-typed-array
Imports
- whichTypedArray
const whichTypedArray = require('which-typed-array');import whichTypedArray from 'which-typed-array';
Quickstart
import whichTypedArray from 'which-typed-array';
console.log(whichTypedArray(new Int8Array())); // 'Int8Array'
console.log(whichTypedArray(new Uint8ClampedArray(10))); // 'Uint8ClampedArray'
console.log(whichTypedArray(new Float64Array([1.1, 2.2]))); // 'Float64Array'
console.log(whichTypedArray([])); // false
console.log(whichTypedArray({})); // false
console.log(whichTypedArray(42)); // false
console.log(whichTypedArray(null)); // false
// Example with BigInt Typed Arrays
if (typeof BigInt64Array !== 'undefined') {
console.log(whichTypedArray(new BigInt64Array([1n, 2n]))); // 'BigInt64Array'
}