Skip to content

Callback parameter type is any for union of arraysΒ #52748

Closed
@steverep

Description

@steverep

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].

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions