Closed
Description
Bug Report
π Search Terms
array, union, callback, any, contextual
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed all FAQ
β― Playground Link
Playground link with relevant code
π» Code
let myCondition = true;
const arr1 = ["a", "b", "c"];
const arr2 = [1, 2, 3];
// Correctly inferred as string[] | number[]
const myArr = myCondition ? arr1 : arr2;
for (const val of myArr) {
// val correctly inferred to string | number
console.log(val);
}
myArr.forEach((val) => {
// val incorrectly inferred as any
console.log(val);
});
π Actual behavior
The for..of
loop correctly infers the type, but array methods (e.g. forEach
, map
, filter
, etc.) infer the array item type to be any
.
π Expected behavior
Given a type which is the union of arrays and/or tuples, T1[] | T2[] | ... Tn[]
, array methods which take functions should infer the item parameter's type as T1[number] | T2[number] | ... Tn[number]
.