Closed
Description
🔎 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
💻 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.