Skip to content

Transpilation of optional chaining combined with type casting results in function call losing its context #44639

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
willgm opened this issue Jun 17, 2021 · 0 comments · Fixed by #44666
Assignees
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue Rescheduled This issue was previously scheduled to an earlier milestone

Comments

@willgm
Copy link

willgm commented Jun 17, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue Rescheduled This issue was previously scheduled to an earlier milestone
Projects
None yet
5 participants