Catch when callbacks are missing a return.
See original GitHub issueSearch Terms
- array callback return
- eslint array-callback-return
- catch missing return for callbacks
Suggestion
TypeScript does not recognise this as an error even though it clearly is - findIndex
takes a callback which should return a boolean, returning an (implicit) undefined
is IMO in 99% of cases a mistake.
[1,2,3].findIndex(e => {
e === 1
})
I also think that if there is an explicit return of a falsey value such as null
or undefined
, then that should be fine. It’s the lack of any return at all which should trigger an error, in my eyes.
I’m aware that ESLint can do this but not everyone uses ESLint, also ESLint can be a huge pain to configure sometimes, especially when Prettier, TypeScript and other things are involved.
Use Cases
It will definitely catch errors, IMHO, for people who don’t use ESLint or do not have the rule array-callback-return
.
Examples
No error:
[1,2,3].findIndex(e =>
e === 1
)
No error:
[1,2,3].findIndex(e => e === 1)
A warning/errror: “Did you forget a return?”
[1,2,3].findIndex(e => {
e === 1
})
Checklist
My suggestion meets these guidelines:
- This wouldn’t be a breaking change in existing TypeScript/JavaScript code
- This wouldn’t change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn’t a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript’s Design Goals.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:5 (3 by maintainers)
Top GitHub Comments
Until and unless this gets implemented, you might consider modifying the standard library typings in your local code base to get something close to this behavior:
Playground link
This is ugly enough that I wouldn’t seriously suggest doing it upstream. Less ugly is just requiring that the callback return
boolean
:Playground link
which also wouldn’t be suitable for upstream because it would likely break a lot of existing code that relies on truthy/falsy returns.
Listing all the types without void would resolve this as follows.