ts-api-utils icon indicating copy to clipboard operation
ts-api-utils copied to clipboard

🚀 Feature: Replace `forEach...` methods with `Iterable`s

Open fisker opened this issue 3 months ago • 3 comments

Bug Report Checklist

  • [x] I have pulled the latest main branch of the repository.
  • [x] I have searched for related issues and found none that matched my issue.

Overview

So we can use for..of and Array.from(), .toArray() instead of callbacks.

For example:

https://github.com/typescript-eslint/typescript-eslint/blob/c1980522cd11f2de1a49ff6a30b4be7765a843ff/packages/typescript-estree/src/convert-comments.ts#L16

This can rewrite as

return Array.from(tsutils.getComments(ast), ...);

or

return tsutils.getComments(ast).map(...).toArray();

Additional Info

No response

fisker avatar Sep 22 '25 22:09 fisker

I like this in theory! It wouldn't even be a breaking change. We could add the new return type and deprecate the callback parameter in the current major version.

Looking at public JS and TS uses of tsutils.forEachComment, only some consumers ignore the first parameter ((_, ast) => {). So I think we'll have to provide Iterable<[fullText: string, comment: ts.CommentRange]> to mirror the callback.

WDYT @kirkwaiblinger @RebeccaStevens?

JoshuaKGoldberg avatar Sep 25 '25 15:09 JoshuaKGoldberg

we'll have to provide Iterable<[fullText: string, comment: ts.CommentRange]> to mirror the callback.

Don't understand why an array with fullText.

An object shape will be easier to uses and extend {range: ts.CommentRange, value: string} or {range: ts.CommentRange, value: string, fullText: string}, or even in the shape that typescript-eslint generates, properties except range should use getter to avoid unnecessary calculations.

fisker avatar Sep 25 '25 16:09 fisker

Looking at convertComments https://github.com/typescript-eslint/typescript-eslint/blob/c1980522cd11f2de1a49ff6a30b4be7765a843ff/packages/typescript-estree/src/convert-comments.ts#L16, it make sense to provide all the properties (maybe except .loc)

fisker avatar Sep 25 '25 16:09 fisker