Skip to content

Fail to short circuit an undefined private class field with optional chaining #38503

@motss

Description

@motss

TypeScript Version: 3.8.3

Search Terms:

  • private method
  • private class field
  • short circuit
  • optional chaining
  • typeerror
  • cannot get property of

Code

     /** Truncated for brevity */
33   // this.#callback?.(this.#list, this); /** Fails to short-circuit with ?. */
34   if (this.#callback) this.#callback(this.#list, this); /** This works fine */
     /** Truncated for brevity */

Expected behavior:

Expected this.#callback?.(this.#list, this) to not execute when this.#callback is nullish.

Actual behavior:

/**
 * Fail to short-circuit with ?. and produces TypeError.
 * Expected it to behave just like:
 * 
 *   if (this.#callback) this.#callback(this.#list, this);
 *
 */
this.#callback?.(this.#list, this);
Uncaught TypeError: Cannot read property 'call' of undefined
    at A.add (eval at <anonymous> (main-3.js:1239), <anonymous>:42:62)
    at eval (eval at <anonymous> (main-3.js:1239), <anonymous>:54:3)
    at main-3.js:1239

Playground Link:

Run the reduced test case in TypeScript playground and see the result in DevTools.
Comment and uncomment L33 and L34 to see the different results when they should behave the same.

Related Issues:
Tried to look up but could not find one.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issueRescheduledThis issue was previously scheduled to an earlier milestone

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions