google / google/closure-compiler

"this:" in @typedef fails to suppress `JSC_USED_GLOBAL_THIS` warnings in functions declared with @type

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

Description

When declaring functions using @type {TypedefedName}, as in the following example:

```JS
/** @constructor */
function Foo() {
this.bar = 42;
}

/** @typedef {function(this: Foo): number} */
Foo.funcType;

/** @const {Object} */
var funcs = {};

/** @type {Foo.funcType} */
funcs['baz'] = function () {
return this.bar;
}
```
…I get an unexpected warning:
```
Number of warnings: 1

JSC_USED_GLOBAL_THIS: dangerous use of the global this object at line 20 character 9
return this.bar;
^
```
In `baz`, the compiler seems to understand that `this` is a `Foo`, because it will complain if I attempt to assign a string to `this.bar`, but it still emits the global this warning anyway.

(I can make the warning go away by explicitly declaring `baz` like this:
```JS
/**
* @this {!Foo}
* @return {number}
*/
funcs['baz'] = function () {
return this.bar;
}
```
…but I have many such baz to define, each of which, in reality, has a long list of parameters, and it would be preferable not to repeat the full type declaration for each one.)

This occurs in v20180204 as well as [the current version on closure-compiler.appspot.com](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%252F%2520ADD%2520YOUR%2520CODE%2520HERE%250A%250A%252F**%250A%2520*%2520%2540constructor%250A%2520*%252F%250Afunction%2520Foo()%2520%257B%250A%2520%2520this.bar%2520%253D%252042%253B%250A%257D%250A%250A%252F**%250A%2520*%2520%2540typedef%2520%257Bfunction(this%253A%2520Foo)%253A%2520number%257D%250A%2520*%252F%250AFoo.funcType%253B%250A%250A%252F**%2520%2540const%2520%257BObject%253Cstring%252C%2520Foo.funcType%253E%257D%2520*%252F%250Avar%2520funcs%2520%253D%2520%257B%257D%253B%250A%250A%252F**%2520%2540type%2520%257BFoo.funcType%257D%2520*%252F%250Afuncs%255B'baz'%255D%2520%253D%2520function%2520()%2520%257B%250A%2520%2520return%2520this.bar%253B%250A%257D%250A) when **advanced optimisations** are enabled.

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.