google / closure-compiler

A JavaScript checker and optimizer.
https://developers.google.com/closure/compiler/
Apache License 2.0
7.4k stars 1.15k forks source link

Type checking const "this.*" incorrectly checks outside of scope where names overlap #4197

Open hills opened 1 week ago

hills commented 1 week ago

In this minimal test case the compiler seems to be (incorrectly) type checking against a variable declared outside the scope?

$ java -jar closure-compiler-v20240317.jar -O ADVANCED  test.js
test.js:14:4: WARNING - [JSC_TYPE_MISMATCH] assignment to property zzz of MyObject
found   : function(boolean): undefined
required: function(number): undefined
  14|     this.zzz = zzz;
          ^^^^^^^^^^^^^^

0 error(s), 1 warning(s), 100.0% typed
/**
 * @param {!number} w
 */

function zzz(w) {     // this function should be irrelevant
}

/**
 * @constructor
 */

function MyObject() {
    /** @const */
    this.zzz = zzz;   // fails the type check

    /**
     * @param {boolean} v
     */

    function zzz(v) {
    }
}
brad4d commented 1 week ago

Yep, that's a bug!

Thanks for reporting it.

brad4d commented 1 week ago

If the inner function zzz() declaration gets moved above the this.zzz = zzz; assignment, the error no longer appears. It seems like the type checking is failing to take function hoisting into account.