Skip to content
Advertisement

TypeScript function that works on all numerical array types

I am trying to write a function that works on all of the JavaScript array types, e.g. on number[], Float32Array etc. It should return the same type that it gets as a parameter. A simple example would be:

JavaScript

The function should be able to use all methods common to all array types (not just map).

I also tried

JavaScript

but I get

JavaScript

What would the TypeScript signature of such a function be? I also want to be able to create several such function and pass them as a parameter to another function (all properly typed, of course). A trivial example would be:

JavaScript

The type of a should define which signature of func is used. I have no problems running this in JS, but when trying to add proper TS typing, the TS compiler complains (I am running with "strict": true compiler option).

Advertisement

Answer

TypeScript does not have a built-in NumericArray type of which Array<number> and Float32Array-et-cetera are subtypes that gives you access to all common methods. Nor can I think of a one-or-two line solution that will give that to you. Instead, if you really need this, I’d suggest you create your own type. For example:

JavaScript

That’s kind of long, but I created it by merging the existing array typings in lib.es5.d.ts, and changing any reference to the particular array type with the polymorphic this type, meaning “the current subtype of the NumericArray interface”. So, for example, Array<number>‘s map() method returns an Array<number>, while a Float32Array‘s map() method returns a Float32Array. The this type can be used to represent this relationship between the array type and the return type.

If you care about post-ES5 functionality you can go and merge those methods in also, but this should be enough to demonstrate the basic approach.

You could try to write something that computes NumericArray programmatically, but I wouldn’t want to. It is likely to be more fragile and more confusing than the manual NumericArray definition above, and probably take nearly as many lines.


Then, I’d write your addOne() in terms of NumericArray:

JavaScript

And you can verify that it works as expected for Array<number> and Float32Array:

JavaScript

And your doSomethingWithArray would look like this:

JavaScript

Looks good!

Playground link to code

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement