TypeScript: "TypedArray" interface for Typed Arrays

Viewed 1551

How do I tell TypeScript that given parameter contains one of the Typed Arrays?

It is not uncommon to have the ability to choose the type of Typed Array that best suits your needs (for instance the Flatbush library does this).

I want to check if what is passed into the constructor indeed identifies one of the Typed Arrays. But in my lib.es6.d.ts none of the Typed Arrays inherit from a common interface.

related question: What is the "ArrayLike" interface used for?

3 Answers

typescript doesn't have a TypedArray interface but like the suggestion here, you can use ArrayBufferView which is a supertype of all typed arrays.

There is no built-in alias, but you can create one yourself based on the types from lib.es2017.typedarrays.d.ts.

type TypedArray =
  | Int8Array
  | Uint8Array
  | Uint8ClampedArray
  | Int16Array
  | Uint16Array
  | Int32Array
  | Uint32Array
  | Float32Array
  | Float64Array;

To answer your second question: not every collection used in the browser is implemented with proper arrays. Some data structures like NodeListOf or AggregateError have different methods on them, but share one similarity — they can be indexed by numbers. You can think of ArrayLike as an abstract type used to describe such an object.

If you're not happy using ArrayBufferView, as per @tobenna's answer, the only other option would be to create your own TypedArray interface.

type TypedArray =
  | Int8Array
  | Uint8Array
  | Uint8ClampedArray
  | Int16Array
  | Uint16Array
  | Int32Array
  | Uint32Array
  | Float32Array
  | Float64Array;

Note: unlike the ArrayBufferView method, this excludes DataView objects.

Finally, the ArrayLike interface is used for everything that can be indexed by a number and has a length. This includes things like the DOM NodeList, which doesn't contain the majority of methods on the Array prototype.

Related