google / google/closure-compiler

Type information on ES6 'const' variables doesn't propagate to closures

Open
#1,336 6 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
7.7k
Forks
1.2k
Avg merge
2d 12h
Merged PRs (30d)
6

Description

[sandbox demo](https://closure-compiler.appspot.com/home#code%3D%252F%252F%2520%253D%253DClosureCompiler%253D%253D%250A%252F%252F%2520%2540compilation_level%2520ADVANCED_OPTIMIZATIONS%250A%252F%252F%2520%2540output_file_name%2520default.js%250A%252F%252F%2520%253D%253D%252FClosureCompiler%253D%253D%250A%250A%252F**%250A%2520*%2520%2540param%2520%257B!Element%257D%2520el%250A%2520*%252F%250Afunction%2520otherFunction%28el%29%2520%257B%250A%2520%2520console.log%28el%29%253B%250A%257D%250A%250Afunction%2520hello%28name%29%2520%257B%250A%2520%2520const%2520el%2520%253D%2520document.getElementById%28name%29%253B%250A%2520%2520if%2520%28!el%29%2520%257B%250A%2520%2520%2520%2520%252F%252F%2520This%2520%28or%2520goog.asserts.assert%252C%2520etc%29%2520should%2520hint%2520the%2520type%2520is%2520non-nullable.%250A%2520%2520%2520%2520return%253B%250A%2520%2520%257D%250A%250A%2520%2520%252F%252F%2520This%2520works%2520ok%252C%2520as%2520the%2520compiler%2520knows%2520its%2520!Element.%250A%2520%2520otherFunction%28el%29%253B%250A%2520%2520%252F%252F%2520This%2520fails%252C%2520as%2520'el'%2520is%2520treated%2520as%2520if%2520it%2520was%2520a%2520var%2520and%2520could%2520have%2520changed%253F%250A%2520%2520setTimeout%28%28%29%2520%253D%253E%2520otherFunction%28el%29%29%253B%250A%250A%2520%2520%252F%252F%2520Explicitly%2520setting%2520the%2520type%2520to%2520non-nullable...%250A%2520%2520const%2520notNullEl%2520%253D%2520%252F**%2520%2540type%2520%257B!Element%257D%2520*%252F%2520%28el%29%253B%250A%2520%2520%252F%252F%2520...works!%2520So%2520it%2520looks%2520like%2520it's%2520the%2520implicit%2520!%2520that's%2520busted.%250A%2520%2520setTimeout%28%28%29%2520%253D%253E%2520otherFunction%28notNullEl%29%29%253B%250A%257D%250Ahello%28'New%2520user'%29%253B%250A)

Adding nullability information to variables by doing null checks/goog.assert/etc currently gets lost on const variables when moving into closures that capture them. This behavior is desirable with var/let, however with const it should propagate as if the variable has been verified as non-nullable it cannot be changed to null (or any other value).

Boiled down:

``` js
const el = document.createElement('div');
if (!el) return;
setTimeout(() => acceptElement(el)); <-- fails if @param requires non-null type
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.