Typescript: Warn on `forEach(async`

Created on 19 Nov 2018  路  3Comments  路  Source: microsoft/TypeScript

Search Terms

  • forEach
  • forEach(async

Suggestion

A simple warning when someone uses forEach(async. It's such an easy stumbling block for those entering the async/await world. A user never wants to write that code intentionally

Use Cases

I didn't know that forEach(async ... simply doesn't work (even though linting passes, and similar things like .map(async and relatives are fine.

Examples

Wherever the parser encounters forEach(async it marks it as an error.

Checklist

My suggestion meets these guidelines:

  • [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [x] This wouldn't change the runtime behavior of existing JavaScript code
  • [x] This could be implemented without emitting different JS based on the types of the expressions
  • [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [x] This feature would agree with the rest of TypeScript's Design Goals.
External

Most helpful comment

It turns out it's not too difficult to implement. So there you have it: https://github.com/fimbullinter/wotan/blob/master/packages/mimir/docs/async-function-assignability.md
This rule does exactly what is asked for in the opening post. It covers a lot more cases and should detect almost all assignments of async functions to void-returning functions.

Have a look at the documentation of the linter for a quick start guide: https://github.com/fimbullinter/wotan/blob/master/packages/wotan/README.md

All 3 comments

I think this is _probably_ the domain of a new lint rule - generally speaking, any non-undefined returning function used with Array.prototype.forEach is _probably_ an error, since the return type is unused, but there's technically nothing wrong with it - forEach'ing over a function with a real-valued return type (eg, Promise) for sideeffects is potentially valid.

It turns out it's not too difficult to implement. So there you have it: https://github.com/fimbullinter/wotan/blob/master/packages/mimir/docs/async-function-assignability.md
This rule does exactly what is asked for in the opening post. It covers a lot more cases and should detect almost all assignments of async functions to void-returning functions.

Have a look at the documentation of the linter for a quick start guide: https://github.com/fimbullinter/wotan/blob/master/packages/wotan/README.md

that is @ajafff would love to get that into our codebase... so you know, i can stop making terrible bugs for myself 馃槅

Was this page helpful?
0 / 5 - 0 ratings

Related issues

blakeembrey picture blakeembrey  路  171Comments

Taytay picture Taytay  路  174Comments

metaweta picture metaweta  路  140Comments

kimamula picture kimamula  路  147Comments

Gaelan picture Gaelan  路  231Comments