microsoft/TypeScript

3.4 globalThis support makes incorrect assumptions about let/const bindings

shicks opened this issue · 2 comments

TypeScript Version: 3.4.0-dev.20190316

Search Terms:
3.4 globalThis let const property

Code

// Compile with `tsc -t es2015`
const foo: number = 42;
const bar: null = globalThis.foo; // Type 'number' is not assignable to type 'null';

For reference, the following demonstrates how these bindings behave in browser and node, respectively:

<script>
const foo = 42;
alert(window.foo); // --> "undefined"
</script>
const foo = 42;
console.log(global.foo); // --> "undefined"

Expected behavior:
TypeScript models types consistently with what's actually happening in VMs. Specifically, variables bound by let or const are not translated to properties on globalThis.

Actual behavior:
TypeScript converts let/const bindings onto properties of globalThis, but these properties do not exist in ES2015+ output (when let and const are retained in the output).

This is a problem because it enables coding patterns that depend on transpilation to ES5 or lower to work correctly. When the output level is switched to ES2015, these will break at runtime with no compile-time warning.

Playground Link:
N/A: playground does not support 3.4 yet

Related Issues:
None found

Verified, and checked with MDN. Not sure how that is going to translate to our var-declared classes in our .d.ts files.

The lib.d.ts file that changes the most is es5.d.ts, with Function, String, et al declare const instead of declare var. Bigint from esnext also changes, and that's it.

After some discussion, I vote for shipping as-is and then adding the restriction for 3.5, along with changes to d.ts.

I don't think being incorrectly permissive is going to cause problems given how permissive global used to be, and the risk of changing Function et al from const to var seems scary to me.