I’d like to use TypeScript to declare functions with parameters that can be either a regular JavaScript Array, or a Typed Array, but I can’t find a nice way to do it. I was hoping that an interface like:
interface IArray
{
length: number;
[index: number]: number;
};
would let me declare a function:
declare var vAdd: { (a: IArray, b: IArray): IArray; };
and use it in any of the following ways:
var y;
y = vAdd(new Float32Array([1,2,3]), new Float32Array([1,2,3]));
y = vAdd([1,2,3], new Float32Array([1,2,3]));
y = vAdd(new Float32Array([1,2,3]), new Array(1,2,3));
… etc. However, only the first line here works (in the TypeScript playground, at least). The others generate an error saying the arguments don’t match the function signature.
By overloading the function it can be made to work:
declare var vAdd: { (a: IArray, b: IArray): IArray;
(a: number[], b: IArray): IArray;
(a: IArray, b: number[]): IArray;
(a: number[], b: number[]): IArray; };
but I’m wondering if there is a way I can avoid writing out all combinations of IArray and number[], which will get even more tedious for functions with more parameters. Or is there something fundamentally wrong with what I’m trying to do?
Check out Possible to define indexer interface for number[]?
There is a bug in the current ts release that doesnt allow indexer interfaces to compile and work as expected against native object arrays.