Skip to content

fix: correct JSDoc comment positioning in type literal members#217

Open
benpsnyder wants to merge 1 commit intosxzz:mainfrom
benpsnyder:fix/jsdoc-comment-association
Open

fix: correct JSDoc comment positioning in type literal members#217
benpsnyder wants to merge 1 commit intosxzz:mainfrom
benpsnyder:fix/jsdoc-comment-association

Conversation

@benpsnyder
Copy link
Copy Markdown

Problem

Single-line JSDoc comments on type alias members get rendered inline instead of on their own line:

// Input
export type B = {
  /** Comment B1 */
  BA?: string;
  /** Comment B2 */
  BB?: string;
};

// Output (before fix)
type B = {
  /** Comment B1 */BA?: string; /** Comment B2 */
  BB?: string;
};

// Output (after fix)
type B = {
  /** Comment B1 */
  BA?: string;
  /** Comment B2 */
  BB?: string;
};

Interface members are unaffected — only type alias object members have this issue.

Root Cause

Babel's @babel/generator has special-case newline handling for comments inside TSInterfaceBody but not TSTypeLiteral (source). When loc is deleted from AST nodes (which the plugin needs for source map correctness — see e9d69ef), the generator falls through to a heuristic code path that skips newlines before single-line comments in type literals.

Fix

After deleting loc from AST nodes, assign synthetic sequential line numbers to nodes that have leading comments. This steers Babel's generator into the loc-aware code path which correctly inserts newlines before comments regardless of the parent node type. The original comment column positions are preserved to maintain indentation.

Related

Test plan

  • New jsdoc-members test fixture covering both interface and type alias members with single-line and multi-line JSDoc comments
  • Existing jsdoc test unchanged (no snapshot diff)
  • Full test suite passes (197 passed, 1 expected fail)
  • No source map regressions

Single-line JSDoc comments on type alias members (e.g. `type B = {
/** comment */ foo: string }`) were rendered inline instead of on their
own line. This happened because Babel's generator only special-cases
`TSInterfaceBody` for comment newline insertion, not `TSTypeLiteral`.

When `loc` was deleted from AST nodes (needed for source map
correctness), Babel's generator fell through to a code path that skips
newlines before comments in type literals. The fix assigns synthetic
sequential line numbers to nodes with leading comments, which steers
Babel's generator into the loc-aware code path that correctly positions
comments on separate lines.

Closes sxzz#182

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JSDoc comments misplaced in types

1 participant