Question

I'm having an issue with closure compiler where it's not enforcing strict type checks for some strange reason. It correctly checks type safety when setting a variable where it's declared, but is failing to throw an type error when passing an object.

/**
 *  @public
 *  @param x {number}
 */
SomeClass.prototype.setterMethod = function(x) {

    this.var1 = x;

};

var a = new SomeClass();
a.setterMethod({}); // SHOULD THROW AN ERROR!!!!!!

Why isn't closure compiler enforcing type safety here? It correctly functions if I declare the variable:

this.var1 = {};  // correctly throws an error

However it is not enforcing strict type safety checks on function parameters, or when setting the class member variable outside of the member declaration. I've posted the full code and output below. Is there a way to force closure to force these types of checks? Or am I doing something wrong here?

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @warning_level VERBOSE
// @output_file_name default.js
// ==/ClosureCompiler==

/**
 *  @class SomeClass
 *  @constructor
 */
function SomeClass() {

    /**
     *  @protected
     *  @type {number}
     */
    this.var1;

};

/**
 *  @public
 *  @param x {number}
 */
SomeClass.prototype.setterMethod = function(x) {
    this.var1 = x;
};

/**
 *  @public
 *  @returns {number}
 */
SomeClass.prototype.getterMethod = function() {
    return this.var1;
};

/**
 *  @type {SomeClass}
 */
var a = new SomeClass();
a.setterMethod({});
console.log(a.getterMethod());

// output: -- NO WARNINGS!!!!
// var a=new function(){};a.a={};console.log(a.a);
Was it helpful?

Solution

There are two issues occurring:

  1. The Closure-compiler web service runs in a type of "demo" mode and assumes all undeclared variables are external. There is currently no way to disable this. Testing with the command line compiler doesn't show the same issues.

  2. Your JSDoc paramater annotation is not correct. It should be @param {number} x (you have the type and name reversed).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top