Closed
Description
Bug Report
🔎 Search Terms
optional chaining, type casting, transpiling
🕗 Version & Regression Information
When transpiling the optional chaining feature on a method class and combining it to a type casting, the generated code makes the function call loses its context (this
).
The same does not occur when transpiling the optional chaining feature without the type casting, or if you use type casting without transpiled optional chaining.
The behavior is the same since optional chaining was introduced to TypeScript since version 3.7.
⏯ Playground Link
Playground link with relevant code
💻 Code
Original TypeScript code:
class Teste {
teste() {
return 666;
}
}
const t = new Teste();
// Buggy behavior:
// type casting and optional chaining combined makes function call loses instance context
(t.teste as any)?.();
// Correct behaviors:
// the same features used individually does not make the function call loses instance context
(t.teste as any)();
(t.teste)?.();
Transpiles to:
"use strict";
var _a, _b, _c;
class Teste {
teste() {
return 666;
}
}
const t = new Teste();
// Buggy behavior:
// type casting and optional chaining combined makes function call loses instance context
(_a = t.teste) === null || _a === void 0 ? void 0 : _a();
// Correct behaviors:
// the same features used individually does not make the function call loses instance context
t.teste();
(_c = ((_b = t).teste)) === null || _c === void 0 ? void 0 : _c.call(_b);
🙂 Expected behavior
I believe that type casting should not make transpilation generates different code with different behavior for optional chaining or any other feature.