microsoft / microsoft/TypeScript
Support "evolving any" with forEach / internal functions
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
TypeScript 2.1 introduced the notion of an "evolving" any type, a variable whose type is determined based on subsequent usage:
function square(xs: number[]) {
const ys = [];
for (const x of xs) {
ys.push(x * x);
}
return ys; // type is number[], hooray!
}
Unfortunately this is a bit brittle. If you ever introduce an internal function (say if you use forEach) then the inferred type is lost and you get a no implicit any error:
function square(xs: number[]) {
const ys = []; // Variable 'ys' implicitly has type 'any[]' in some locations
// where its type cannot be determined. (7034)
xs.forEach(x => {
ys.push(x * x);
});
return ys; // Variable 'ys' implicitly has an 'any[]' type. (7005)
}
The two forms do the same thing, so it's somewhat surprising that the for-of version passes the type checker but the forEach version does not.
I find the "evolving any" construct to be incredibly useful, but I have to scrap it every time I introduce an arrow function. I'm proposing that it be extended to work for cases like this.
TypeScript 3.7.2
Playground link
Expected behavior:
I'd expect both versions to pass the type checker and infer the type of ys as number[].
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked Playground example and compare the for-of and forEach forms described in the issue. The change is complete when both forms pass the type checker and infer ys as number[] without implicit-any errors.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100