Skip to content

Downlevel optional chaining loses this for parenthesized callees with !, as or type arguments, and for parenthesized template tags #65597

Open

Description

This issue was drafted with the help of LLMs (Claude and Codex); I reviewed it and verified the reproductions.

TypeScript Version

The tested TypeScript version is 7.1.0-dev.20261119.1 (typescript@next on November 20, 2026). 7.0.2 and 6.0.3 print the same, and the first five lines print false in every version I tried, back to 3.7.2.

User Goal

We ran into (obj?.fn!)?.() losing this while testing optional method calls in core-js, and then checked which other callee shapes do the same.

Setup and Action

Save as repro.mts:

const obj = {
  fn(..._args: unknown[]) { return this; },
};

console.log((obj?.fn!)?.() === obj);
console.log((obj.fn!)?.() === obj);
console.log((obj?.fn!)() === obj);
console.log((obj?.fn as any)() === obj);
console.log((obj?.fn)`x` === obj);
console.log((obj?.fn)?.() === obj);
console.log((obj?.fn)() === obj);
console.log((obj.fn as any)?.() === obj);
npx --yes --package=typescript@7.1.0-dev.20261119.1 tsc --ignoreConfig --target es2019 --outDir out repro.mts
node out/repro.mjs

Playground with TypeScript 6.0.3 and the ES2019 target

Expected and Actual Behavior

What actually happened: The first five lines print false, so the method got this === undefined, and the last three print true. The first five calls are emitted without a receiver: the optional calls end in _a() and _b(), the plain calls are (obj === null || obj === void 0 ? void 0 : obj.fn)(), and the tag is (obj === null || obj === void 0 ? void 0 : obj.fn) `x`. The last three end in _c.call(obj), .call(obj) and _d.call(obj).

What I expected: All eight lines print true, as they do with node repro.mts on Node.js 26.13.0 and with --target es2020. ! and as are type-only, and a parenthesized member access keeps its this when it is called or used as a tag.

Other callee shapes lose this the same way: (super.fn!)?.(), (obj.fn<string>)?.() for a generic fn, (obj?.fn)!(), (obj?.fn satisfies unknown)() and (obj?.["fn"])`x`. #35476 and #44639 fixed the last two lines of the repro, and #65414 reports the same callee shapes for imported functions in CommonJS output.

Agent Info

Codex CLI 0.166.0 + GPT-6.2 Astra; Claude Code in Claude desktop 6.6395.1 + Claude Opus 5.5; Skill Version 1.0

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions