Typescript: optional chaining with not defined variable

Created on 1 Apr 2020  路  5Comments  路  Source: microsoft/TypeScript


TypeScript Version: 3.7.x-dev.201xxxxx


Search Terms:

Code

// @ts-ignore
console.log(window?.a)

Expected behavior:

// @ts-ignore
"use strict";
// @ts-ignore
console.log(typeof window === 'undefined' || window === null ? void 0 : window.a);

Actual behavior:

ReferenceError: window is not defined

// @ts-ignore
"use strict";
// @ts-ignore
console.log(window === null || window === void 0 ? void 0 : window.a);

Playground Link:

Related Issues:

Working as Intended

Most helpful comment

Typescript isn't going to change the runtime behavior of ?. to be different than the ECMAScript spec.

If you have globalThis or a polyfill of it available, you could write

globalThis?.window?.a

All 5 comments

ReferenceError is the correct result per the spec. Unlike typeof operator, evaluation of optional chaining does not include any special treatment of references to undeclared variables.

Chrome result:
chrome-optional-chaining

nit: Nullish Coalescing refers to ??, not ?.

The key thing in the spec here is that when you evaluate foo?.bar, foo is evaluated by normal means with no special behavior for optional chaining. It's only the ?.bar part that is different than .bar.

if can't avoid not defined variable error

code will become this, i think this not good thing

console.log(typeof window !== 'undefined' && window?.a)

so i hope can replace window === void 0 => typeof window === 'undefined'

Typescript isn't going to change the runtime behavior of ?. to be different than the ECMAScript spec.

If you have globalThis or a polyfill of it available, you could write

globalThis?.window?.a

We'd really ask that you do some due diligence before logging issues. We're pretty clear about TS matching JS behavior, and this is JS behavior you can try in major browsers' consoles without any extra effort.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kyasbal-1994 picture kyasbal-1994  路  3Comments

bgrieder picture bgrieder  路  3Comments

blendsdk picture blendsdk  路  3Comments

siddjain picture siddjain  路  3Comments

CyrusNajmabadi picture CyrusNajmabadi  路  3Comments