Search code examples
javascriptgoogle-closure-compilerjsdocjslintjshint

jsLint weird assignment error when casting


I use google-closure compiler and jsLint tool for my JS code. Because closure compiler looks at JSDoc tags I need to cast variable to proper type or otherwise compiler will throw errors. Code below works ok (no compiler warnings), but when I run jsLint I get 'Weird assignment' error. Is there any other way to cast variable.

/** @return {Town|Village|Park|Metropolis} */
var getCurrentItem = function() {...some code}

var item = getCurrentItem();

if (condition)
{
    item = /** @type {Town} */ (item);  // 'Weird assignment' error occurs

    drawTown(item);
    updateTown(item)
}
else
{
    item = /** @type {Village} */ (item);  // 'Weird assignment' error occurs

    drawVillage(item);
    updateVillage(item)
}

I want casting to be done in one line and not on every function that I need to call!


Solution

  • I'd like to provide you with a few thoughts;

    1) From Writing Resilient Components/#marie-kondo-your-lint-config:

    Here’s what I suggest you to do on Monday. Gather your team for half an hour, go through every lint rule enabled in your project’s config, and ask yourself: “Has this rule ever helped us catch a bug?” If not, turn it off.

    2) Closure Compiler has no issue with your code.

    3) Just cast twice if you must:

    drawVillage(/** @type {Village} */ (item));
    updateVillage(/** @type {Village} */ (item));
    

    4) If you're really quite concerned about avoiding repeating yourself, you can create a function that does the casting for you;

    /** 
     * @param {Town|Village|Park|Metropolis} p
     * @return {boolean|Village}
     */
    var getVillage = function(p) {
      if (p.somethingVillageSpecific) {
        return /** @type {Village} */ (p);
      } else {
        return false;
      } 
    }
    

    5) Lint with ES-lint + jsdocs-plugin.