I have come across a typings declaration that caught my attention:
public static Loop<Type>(arr:Type[], callback:(obj:Type) => void):void;
This declaration represents the structure of a function written in native JavaScript. It essentially iterates through each element in an array and executes a callback function on it, like so:
Loop(["hello", "world"], function(value)
{
console.log(value);
});
While I am able to utilize intellisense when using it as shown in the example above, I'm encountering an issue when attempting to use it with arrays containing different data types, for instance:
let arr: string[] | number[] = [];
Loop(arr, function(value)
{
console.log(value);
});
Unfortunately, the above setup does not function as intended - the variable "value" is categorized as type 'any' rather than being restricted to "string" or "number".
On the other hand, if I define the array as let arr: (string|number)[]
, everything falls into place. However, I am not keen on dealing with arrays that consist of a mix of data types. I prefer keeping it either entirely strings or entirely numbers.
Is there a way for me to modify the Loop signature to accommodate scenarios like string[] | number[]
?
-- Your assistance is greatly appreciated