【问题标题】:jsLint weird assignment error when casting投射时jsLint奇怪的分配错误
【发布时间】:2019-10-01 05:37:22
【问题描述】:

我对我的 JS 代码使用 google-closure 编译器和 jsLint 工具。因为闭包编译器查看 JSDoc 标签,所以我需要将变量转换为正确的类型,否则编译器会抛出错误。下面的代码可以正常工作(没有编译器警告),但是当我运行 jsLint 时出现“奇怪的分配”错误。有没有其他方法可以转换变量。

/** @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)
}

我希望在一行中完成转换,而不是在我需要调用的每个函数上完成!

【问题讨论】:

  • 查看github.com/jamesallardice/jslint-error-explanations/blob/master/… 听起来您需要一种方法来记录item 的类型,而无需重新分配它
  • 你在使用gjslint吗?现在已弃用:github.com/google/closure-linter
  • @CertainPerformance 你是对的。我知道在 javascript 中为自身分配变量没有意义,但我需要它来进行转换。不幸的是,您的链接仅适用于 window.location 或其他浏览器全局变量。
  • @johnlinp 不。我没有使用 gjsLint。
  • @royalBlue 我明白了。

标签: javascript google-closure-compiler jsdoc jslint jshint


【解决方案1】:

我想为您提供一些想法;

1) 来自Writing Resilient Components/#marie-kondo-your-lint-config

这是我建议你在星期一做的事情。召集你的团队半小时,检查项目配置中启用的每条 lint 规则,然后问自己:“这条规则有没有帮助我们发现错误?”如果没有,请关闭它。

2)Closure Compiler has no issue with your code.

3) 如果必须,只需施放两次:

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

4) 如果你真的很担心避免重复自己,你可以创建一个函数来为你进行转换;

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

5) 使用 ES-lint + jsdocs-plugin 进行 Lint。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-26
    • 2011-12-16
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多