Skip to content

(Set | Array).forEach loses type inference for callback #37453

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
iansan5653 opened this issue Mar 18, 2020 · 1 comment
Closed

(Set | Array).forEach loses type inference for callback #37453

iansan5653 opened this issue Mar 18, 2020 · 1 comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@iansan5653
Copy link

iansan5653 commented Mar 18, 2020

Code

type ListOfNumbers = Set<number> | number[];

function iterates(list: ListOfNumbers) {
  list.forEach(element => {
    element; // has type any
  });
}

Expected behavior:

The type of element should be number, because the type of forEach should be:

type ForEachSetOrArray<T> = (current: T, index: T | number, list: Set<T> | Array<T>) => void;

Note: The type of index is not a mistake - Set gives the current value twice, while Array gives the current index. It's weird.

Actual behavior:

The type of element is inferred to be any and has to be explicitly stated as number.

Playground Link: https://www.typescriptlang.org/play/?ssl=1&ssc=9&pln=1&pc=1#code/C4TwDgpgBAMglgZ2AeQGYDkCuBbARhAJwSgF4oBlCYAHgDsd8CA+KAHynr0IG0BdAbgCwAKBGpMtAMbA4Ae1pQ4wQgENlCABQAbRMABcsXWixciASigBvEVCg6kAOlSyCAURWSAFhohaI2CFpgUhZrYVtbX39A4H4oAHp4qE8VYlBIKBVaEBsoAF8zIWE8oA

@RyanCavanaugh RyanCavanaugh added the Design Limitation Constraints of the existing architecture prevent this from being fixed label Mar 18, 2020
@RyanCavanaugh
Copy link
Member

We're only capable of combining contextual types when the source signatures come from the same declaration; making the parameters line up in the first position wouldn't be sufficient here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

2 participants