Search code examples
javascriptgoogle-closure-compilergoogle-closure

typedef of this variable doesn't produce warning


I want to produce a warning for a number if a string is assigned to it. So, I thought typedef of Closure might do this for me. I tried the following -

  var Widget = function()
  {
    /** @typedef {number} */
    this.size = null;
  };

  new Widget().size = "kaboom!"

When I compile it using http://closure-compiler.appspot.com/home it doesn't throw a warning or error. What am I doing wrong? And/or what other tool should I be using?


Solution

  • Turn the optimization up to Advanced in the closure compiler service to catch these warnings. You still won't see any for your example (well, you will see some, but not what you are expecting), because typedefs are used to define custom types. Also, you need to annotate your constructor. Run the following example in advanced mode and you will see your warnings. Instead of making a typedef for a simple thing like number, I would just use @type, but this example is to show you the proper use of typedef.

    /** @typedef {number} */
    var customType;
    
    /** @constructor */
    var Widget = function()
    {
      /** @type {customType} */
      this.size = null;
    };
    
    new Widget().size = "kaboom!"