5

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?

1

3 Answers 3

4

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
  | BigInt64Array
  | BigUint64Array;

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.

Edit: Added BigInt64Array | BigUint64Array as per suggestion from @Codesmith

Sign up to request clarification or add additional context in comments.

3 Comments

Be sure to also include BigInt64Array and BigUint64Array which are also typed arrays as of ES2020.
If anyone is looking for a TS type guard, ArrayBuffer.isView() seems to do the job. It returns true if the argument is of type ArrayBufferView
Float16Array was recently added too.
3

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

1 Comment

ArrayBufferView isn't a supertype (union type) of all typed arrays, for example, it doesn't have a length property. Due to this lack of equivalence, one can't perform let a: ArrayBufferView, acc = 0; for(let i = 0; i < a.length; i++) acc += a[i]; because TS will complain that ArrayBufferView has no length property.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.