microsoft / microsoft/TypeScript
Array.prototype.filter doesn't require callback to return
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
I dig a bit and found out in #5850 and subsequently in #7779 the signature of filter has been changed not to return a boolean, so that people could return a truthy value in the implementation of the filter.
While I undertand the convenience in terms of ease of use, this as far as I observed puts developers at risk of simple bugs like the following:
const even = [1,2,3].filter(x => {
x % 2 == 0
})
Notice the missing return statement means the function returns undefined, which translates to false, which filters all the items out. This applies also in the case of noImplicitReturns set to true, since the function return type is any, thus it could be a void function for what the compiler knows.
I believe TypeScript's job should be to put this kind of cases in check actually, so that things like truthy values (which sometimes aren't as obvious as we might think and introduce bugs we don't really understand) can be better taken care of.
One solution to make both parties happy would be to optionally support truthy values (maybe an extra compiler flag? Another truthy type to allow for more relaxed checking?) and reintroduce the original signature of filter.
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 by reviewing the Array.prototype.filter signature and the history in issues #5850 and #7779. Determine whether the requested checking should reject callbacks that omit return statements while preserving the intended truthy-value behavior; the issue is done when the desired type-checking behavior and compatibility trade-offs are specified and covered by appropriate compiler tests.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100