Skip to content

Line comment in type cast incorrectly compiles to early return #59237

Closed
@unflxw

Description

@unflxw

🔎 Search Terms

"comment in type cast"

🕗 Version & Regression Information

This is the behavior in every version I tried (nightly 5.6.0-dev.20240711 via playground, 5.5.3 via playground, 5.4.5 in Node.js 18, 5.4.5 in Node.js 20, 4.9.5 via playground), and I reviewed the FAQ for entries about this issue

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.5.3#code/GYVwdgxgLglg9mABMOcAUBKRBvRAnAUyhDyQBYAmRAXwChaB6BxKACxgGdEATOArsHCgs8MAOZiCeRAENEAFQDKiKXjh4ANI2YAjEMIhwAtgAcYAG34s4iAFLLD3Ai1YzhhYqQ7bEAA3BOwDBgBNy+smDciCEAblKIEDLm5ly+KHC+AIS0oJCwCIjBhniE0JgAXNEgRjrx2LSIjfhEJEhoDU2dTIgcxs6GRkYEYFAdnY3pslyYiAC8AHxVNVJjiBiYtHQ54NDwSMWlUBVLtdL1nR6tiO3jTd29QwnGQyOrnemr6xib9Lm7BUlegB9A4EMoYSpgaqnHCrS6ka6TGTTLALE5SL4-bZ5PayFJwIGAgmg8GQ6F1OEtBE3W7IVBTa6oxZQ5Z4T4bLaGMC9SwAOnMcDEaF8RXUh0qABJsKKSmCjhhqL4MABuWhcnkEfmC4UkqCS7C6zCKlVqhAarVC3xEkFiuX662GhVK1XquB8gWW60O23Qe34wn+x3G5VAA

💻 Code

The issue:

function foo() { return 42 }

// this does not trigger a TS error,
// but compiles to JS code that returns
// `undefined` and never calls `foo`!
function incorrect(): number {
    return (
        // some comment
        foo as () => number
    )()
}

Some cases that don't exhibit the issue:

function correct(): number {
    return (
        // some comment
        foo
    )()
}

function also_correct(): number {
    return (foo as () => number)()
}

function also_also_correct(): number {
    return (
        foo as () => number
    )()
}

For reference, the incorrect function above compiles to the following JS code:

function incorrect() {
    return 
    // some comment
    foo();
}

🙁 Actual behavior

The following code:

return (
    // some comment
    foo as () => number
)()

Compiles to:

return
// some comment
foo()

Where the function returns undefined and foo is never called.

🙂 Expected behavior

It should instead compile to something like:

return (
  // some comment
  foo
)()

This happens, I think, because the compiler attempts to remove unnecessary parenthesis around the type cast, which in this situation turn out not to be unnecessary.

Additional information about the issue

The issue does not occur if removeComments is enabled.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions