Closure Compiler JsDoc 注释替换源代码中的测试?

Closure Compiler JsDoc annotations to replace tests in source code?

JSDoc 注释是否足以测试参数有效性?

示例:在下面的"add"方法中,参数(Point对象)被定义为Non-nullable Point类型。在此方法中并使用 Closure Compiler,然后我可以跳过测试此参数值所需的代码吗:

  1. if (!point) {...
  2. if (!(point instanceof Point)) {...

谢谢

class Point{
  /**
   * Add x/y values to the Point object
   *
   * @param {!Point} point The x/y values to add.
   *
   */
  add(point) {
    this.x += point.x;
    this.y += point.y;
  }
}

是的,前提是正在编译调用该方法的任何代码。

如果您有调用该方法但未被编译的代码,则编译器无法保证传递的类型。例如,如果您创建一个库以供非编译代码调用。在那种情况下,您可能正在导出 add 方法以使其成为 外部非编译代码可访问。

如果您不导出 add 方法,则只有编译后的代码才能访问它。

请参阅 Michael Bolin 的 Checks Provided by the Compiler on page 408 in Closure The Definitive Guide 部分。您需要向编译器指定某些标志,例如:

--jscomp_error=checkTypes
--warning_level=VERBOSE