I am interested in utilizing TypeScript for declaring functions with parameters that can accept either a regular JavaScript Array or a Typed Array. However, I am struggling to find an elegant solution for achieving this flexibility. I thought that defining an interface like:
interface IArray
{
length: number;
[index: number]: number;
};
would allow me to declare a function as follows:
declare var vAdd: { (a: IArray, b: IArray): IArray; };
and then use it in various ways such as:
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));
However, only the first line works correctly in the TypeScript playground. The other lines produce an error indicating that the arguments do not match the function signature.
To make it work, I can overload the function like so:
declare var vAdd: { (a: IArray, b: IArray): IArray;
(a: number[], b: IArray): IArray;
(a: IArray, b: number[]): IArray;
(a: number[], b: number[]): IArray; };
Yet, I am curious if there is a more efficient way to avoid the need to list out all combinations of IArray and number[]. This task could become quite cumbersome, especially for functions with multiple parameters. Is there a fundamental flaw in my approach?